Search code examples
c#.net-4.6.1

handling special characters in textboxes and using splitters


What is a good option when using strings and special characters and splitters?

for example

string name = "test, test";
string result = name + @"test, test";
List<string> list = new List<string>();

lets say i want this string to split and into the list for each item. in this case 'name is an item' and 'test, test' is an item

so i can do something like this:

String.split(list.ToArray(), ',');

i will use the comma as the seperator but both items already contains them aswell.

the result should be:

0 test, test
1 test, test

but since it splits on the comma, the result will be

0 test
1 test
2 test
3 test

to prevent this i can to something like

if(name.Contains(","))
{
    name = name.Replace(",","comma");
}

and then convert back. But i don't like this code it's kinda spaghetti. what i can do instea is make a class translationadapter and 2 methods converter and deconverter

but how do you check for those special characters or what would you suggest in such situation like this. Cause i have got situations like this but with multiple special character like , and #. but i don't want to restrict the textbox.


Solution

  • Three ways to go about it.

    Use a different delimiter

    It's not mandatory to use the , delimiter when joining or splitting strings. That's why some csv files use the ; character: to avoid the comma issue.

    String.Replace() as you did already

    Replace in the individual strings all the characters you want to remain.

    Use a regular expression to split

    If you know that your strings have the same pattern like \d\stest,\stest then you can use the Regex.Split function that uses regular expressions to split the string.