Remove certain letters from input string - c#

I'm currently having a problem where when I search for a code I want to remove the any "."'s a user has inputted. The code I've done doesn't seem to be working and was wondering if someone could tell me why and what I need to do. Thanks.
foreach (var letters in id)
{
string letter = letters.ToString();
if (letter == ".")
{
id.Replace(letter, "");
}
}

String in .NET is an immutable type, therefore you can't change the value of an existing string variable, you need to replace it entirely with the value returned by Replace i.e.
id = id.Replace(letter, "");
FYI you don't have to check whether . is contained in the string, you can just call Replace(".", "") on the resultant string and it will remove any . present i.e.
id = id.Replace(".", "");
See example

String replace method
id = id.Replace(",", "");

Programmaticaly, maybe you can use that besides Replace() method
string m_tempStr = "This.is.a.test";
List<string> myList = new List<string>();
for (int i = 0; i < m_tempStr.Length; i++)
{
if (m_tempStr[i].ToString() != ".")
{
myList.Add(m_tempStr[i].ToString());
}
}
And than, you can get each member of list like following sample code
foreach (var item in myList)
{
Console.Write(item);
}

Related

Converting Arabic Words to Unicode format in C#

I am designing an API where the API user needs Arabic text to be returned in Unicode format, to do so I tried the following:
public static class StringExtensions
{
public static string ToUnicodeString(this string str)
{
StringBuilder sb = new StringBuilder();
foreach (var c in str)
{
sb.Append("\\u" + ((int)c).ToString("X4"));
}
return sb.ToString();
}
}
The issue with the above code that it returns the unicode of letters regardless of its position in word.
Example: let us assume we have the following word:
"سمير" which consists of:
'س' which is written like 'سـ' because it is the first letter in word.
'م' which is written like 'ـمـ' because it is in the middle of word.
'ي' which is written like 'ـيـ' because it is in the middle of word.
'ر' which is written like 'ـر' because it is last letter of word.
The above code returns unicode of { 'س', 'م' , 'ي' , 'ر'} which is:
\u0633\u0645\u064A\u0631
instead of { 'سـ' , 'ـمـ' , 'ـيـ' , 'ـر'} which is
\uFEB3\uFEE4\uFEF4\uFEAE
Any ideas on how to update code to get correct Unicode?
Helpful link
The string is just a sequence of Unicode code points; it does not know the rules of Arabic. You're getting out exactly the data you put in; if you want different data out, then put different data in!
Try this:
Console.WriteLine("\u0633\u0645\u064A\u0631");
Console.WriteLine("\u0633\u0645\u064A\u0631".ToUnicodeString());
Console.WriteLine("\uFEB3\uFEE4\uFEF4\uFEAE");
Console.WriteLine("\uFEB3\uFEE4\uFEF4\uFEAE".ToUnicodeString());
As expected the output is
سمير
\u0633\u0645\u064A\u0631
ﺳﻤﻴﺮ
\uFEB3\uFEE4\uFEF4\uFEAE
Those two sequences of Unicode code points render the same in the browser, but they're different sequences. If you want to write out the second sequence, then don't pass in the first sequence.
Based on Eric's answer I knew how to solve my problem, I have created a solution on Github.
You will find a simple tool to run on Windows, and if you want to use the code in your projects then just copy paste UnicodesTable.cs and Unshaper.cs.
Basically you need a table of Unicodes for each Arabic letter then you can use something like the following extension method.
public static string GetUnShapedUnicode(this string original)
{
original = Regex.Unescape(original.Trim());
var words = original.Split(' ');
StringBuilder builder = new StringBuilder();
var unicodesTable = UnicodesTable.GetArabicGliphes();
foreach (var word in words)
{
string previous = null;
for (int i = 0; i < word.Length; i++)
{
string shapedUnicode = #"\u" + ((int)word[i]).ToString("X4");
if (!unicodesTable.ContainsKey(shapedUnicode))
{
builder.Append(shapedUnicode);
previous = null;
continue;
}
else
{
if (i == 0 || previous == null)
{
builder.Append(unicodesTable[shapedUnicode][1]);
}
else
{
if (i == word.Length - 1)
{
if (!string.IsNullOrEmpty(previous) && unicodesTable[previous][4] == "2")
{
builder.Append(unicodesTable[shapedUnicode][0]);
}
else
builder.Append(unicodesTable[shapedUnicode][3]);
}
else
{
bool previouChar = unicodesTable[previous][4] == "2";
if (previouChar)
builder.Append(unicodesTable[shapedUnicode][1]);
else
builder.Append(unicodesTable[shapedUnicode][2]);
}
}
}
previous = shapedUnicode;
}
if (words.ToList().IndexOf(word) != words.Length - 1)
builder.Append(#"\u" + ((int)' ').ToString("X4"));
}
return builder.ToString();
}

Check string of TextBox.Text does not contain in a string list

I have a Textbox. When i will put any string in textbox, i need to check with below strings. These below strings will come from Database:
string stringList = "\"" + string.Join("\",\"", fetchedString) + "\"";
Output Example: "ABCD1234","EFGH5678","IJKL9101" (These are not fixed strings).
Please help me how will TextBox.Text string will be checked or compared with string list?
It's unclear what you're trying to achieve? Please post an example of some code or what you have tried already.
As it stands, you can get the contents of the text box as a string with the following
TextBox.Text.ToString()
And you should split up stringList into seperate strings using String.Split so that you can iterate through them to compare against your TextBox.
Try this might help you
bool isContain;
foreach (var item in stringList)
{
if (TextBox.Text == item.ToString())
{
isContain = true;
break; //using break depend on your requirement
}
else
{
//Not contain
}
}
You could store your strings in a list and then use Linq to check if they exist already.
var match = listOfStrings.Any(i => i.Equals(Textbox.Text))) ? "Matched" : "Not Matched";

Replacing characters in a string with another string

So what I am trying to do is as follows :
example of a string is A4PC
I am trying to replace for example any occurance of "A" with "[A4]" so I would get and similar any occurance of "4" with "[A4]"
"[A4][A4]PC"
I tried doing a normal Replace on the string but found out I got
"[A[A4]]PC"
string badWordAllVariants =
restriction.Value.Replace("A", "[A4]").Replace("4", "[A4]")
since I have two A's in a row causing an issue.
So I was thinking it would be better rather than the replace on the string I need to do it on a character per character basis and then build up a string again.
Is there anyway in Linq or so to do something like this ?
You don't need any LINQ here - String.Replace works just fine:
string input = "AAPC";
string result = input.Replace("A", "[A4]"); // "[A4][A4]PC"
UPDATE: For your updated requirements I suggest to use regular expression replace
string input = "A4PC";
var result = Regex.Replace(input, "A|4", "[A4]"); // "[A4][A4]PC"
This works well for me:
string x = "AAPC";
string replace = x.Replace("A", "[A4]");
EDIT:
Based on the updated question, the issue is the second replacement. In order to replace multiple strings you will want to do this sequentially:
var original = "AAPC";
// add arbitrary room to allow for more new characters
StringBuilder resultString = new StringBuilder(original.Length + 10);
foreach (char currentChar in original.ToCharArray())
{
if (currentChar == 'A') resultString.Append("[A4]");
else if (currentChar == '4') resultString.Append("[A4]");
else resultString.Append(currentChar);
}
string result = resultString.ToString();
You can run this routine with any replacements you want to make (in this case the letters 'A' and '4' and it should work. If you would want to replace strings the code would be similar in structure but you would need to "look ahead" and probably use a for loop. Hopefully this helps!
By the way - you want to use a string builder here and not strings because strings are static which means space gets allocated every time you loop. (Not good!)
I think this should do the trick
string str = "AA4PC";
string result = Regex.Replace(str, #"(?<Before>[^A4]?)(?<Value>A|4)(?<After>[^A4]?)", (m) =>
{
string before = m.Groups["Before"].Value;
string after = m.Groups["After"].Value;
string value = m.Groups["Value"].Value;
if (before != "[" || after != "]")
{
return "[A4]";
}
return m.ToString();
});
It is going to replace A and 4 that hasn't been replaced yet for [A4].

Writing List<String> contents to text file after deleting string

I'm trying to get the contents of a Text File, delete a line of string, and re-write back to the Text File, deleting the line of string. I'm using StreamReader to get the text, importing into a List, removing the string, then rewriting using StreamWriter. My problems arises somewhere around the removing or writing of the string. Instead of writing back the existing, non deleted contents to the text file, all the text is replaced with :
System.Collections.Generic.List`1[System.String]
My code for this function is as follows:
{
for (int i = deleteDevice.Count - 1; i >= 0; i--)
{
string split = "";
//deleteDevice[i].Split(',').ToString();
List<string> parts = split.Split(',').ToList();
if (parts.Contains(deviceList.SelectedItem.ToString()))
{
deleteDevice.Remove(i.ToString());
}
}
if (deleteDevice.Count != 0) //Error Handling
{
writer.WriteLine(deleteDevice);
}
}
deviceList.Items.Remove(deviceList.SelectedItem);
}
I would just like the script to write back any string that isn't deleted (If there is any), without replacing it. Any help is appreciated, Cheers
You can read all the info from the text file into a list and then remove from the list and rewrite that to the text file.
I would change the list 'deleteDevice' to store a string array instead and use the code below to determine which item to remove.
List<int> toRemove = new List<int>();
int i = 0;
/*build a list of indexes to remove*/
foreach (string[] x in deleteDevice)
{
if (x[0].Contains(deviceList.SelectedItem.ToString()))
{
toRemove.Add(i);
}
i++;
}
/*Remove items from list*/
foreach (int fd in toRemove)
deleteDevice.RemoveAt(fd);
/*write to text file*/
using (StreamWriter writer = new StreamWriter("Devices.txt"))
{
if (deleteDevice.Count != 0) //Error Handling
{
foreach (string[] s in deleteDevice)
{
StringBuilder sb = new StringBuilder();
for (int fds = 0; fds < s.Length; fds++ )
{
sb.Append(s[fds] + ",");
}
string line = sb.ToString();
writer.WriteLine(line.Substring(0, line.Length - 1));
}
}
}
This isn't the best solution but should work for your needs. There's probably a much easier way of doing this.
The problem is in the following line:
writer.WriteLine(deleteDevice);
You're writing deleteDevice (I assume this is of type List). List.ToString() returns the type name of the list, because this has no specific implementation. What you want is
foreach(String s in deleteDevice)
{
writer.WriteLine(s);
}
Problems
deleteDevice is of type List<string>, and because it also doesn't overload ToString(), the default behaviour of List<string>.ToString() is to return the name of the type.
Hence your line writer.WriteLine(deleteDevice); writes the string System.Collections.Generic.List1[System.String]`.
Other than that, there are many things wrong with your code...
For example, you do this:
string split = "";
and then on the line afterwards you do this:
List<string> parts = split.Split(',').ToList();
But because split is "", this will always return an empty list.
Solution
To simplify the code, you could first write a helper method that will remove from a file all the lines that match a specified predicate:
public void RemoveUnwantedLines(string filename, Predicate<string> unwanted)
{
var lines = File.ReadAllLines(filename);
File.WriteAllLines(filename, lines.Where(line => !unwanted(line)));
}
Then you can write the predicate something like this (this might not be quite right; I don't really know exactly what your code is doing because it's not compilable and omits some of the types):
string filename = "My Filename";
string deviceToRemove= deviceList.SelectedItem.ToString();
Predicate<string> unwanted = line =>
line.Split(new [] {','})
.Contains(deviceToRemove);
RemoveUnwantedLines(filename, unwanted);

Find and replace dynamic values via for loop

http://www.test.com/test.aspx?testinfo=&|&
I am trying to replace & with values from a table. I got name and age as two paramaters that I need to substitue and get url like this:
http://www.test.com/test.aspx?testinfo=name|age
If I have 3 string parameters to be replaced for a url:
http://www.test.com/test.aspx?testinfo=&|&
Viz name, age, address for the above url:
http://www.test.com/test.aspx?testinfo=name|age|address
string URL=string.Empty;
URL=http://www.test.com/test.aspx?testinfo=&|&;
//in this case fieldsCount is 2, ie. name and age
for(int i=0; i<fieldsCount.Length-1;i++)
{
URL.Replace("*","name");
}
How do I add "age" so that I get ? any inputs will be helpful.
http://www.test.com/test.aspx?testinfo=name|age
I think this is what you want,
List<string> keys = new List<string>() { "name", "age", "param3" };
string url = "http://www.test.com/test.aspx?testinfo=&|&;";
Regex reg = new Regex("&");
int count = url.Count(p => p == '&');
for (int i = 0; i < count; i++)
{
if (i >= keys.Count)
break;
url = reg.Replace(url, keys[i], 1);
}
I'm curious about two things.
Why are you using & as something to replace, when this has contextual
meaning within the query string as a delimiter between key/value
pairs?
Why does your string have just 2 fields (&|&), when sometimes
the value to replace it with has more than 2 keys?
If these things don't matter, it would make more sense to me to have a replacement string of something else... for instance http://www.test.com/test.aspx?testinfo=[testinfo]. Of course, you need to choose something that has 0 chance of showing up in your Url apart from where you expect it. You can then replace it with something like the following:
url = url.Replace("[testinfo]", string.Join("|", fieldsCount));
Note that this doesn't require your for-loop, and should result in your expected url.
See string.Join on msdn.
Concatenates all the elements of a string array, using the specified
separator between each element.
If I understood right, I think you need something like this:
private static string SubstituteAmpersands(string url, string[] substitutes)
{
StringBuilder result = new StringBuilder();
int substitutesIndex = 0;
foreach (char c in url)
{
if (c == '&' && substitutesIndex < substitutes.Length)
result.Append(substitutes[substitutesIndex++]);
else
result.Append(c);
}
return result.ToString();
}

Categories

Resources