My goal is to make a very simple program that will remove specified characters and thus unite some string. You can see the code below. Delimiters are: whitespace, \n and \t. What actually bothers me is that Split() method gives String.Empty when it sees the delimiter character at the very beggining and end of the string or it also gives String.Empty() if it sees the delimiter twice (for instance two consecutive whitespaces). I am sure that their is a good reason for this which I don't quite understand but what bothers me is how the program below with the help of the method RemoveSpecifiedCharacters correctly ignores (it looks like it "deletes" them but actually it just ignores them) this empty strings (especially two \t\t) which are like whitespaces and totally concatenates all of the strings from substrings array into a new string by the name s2? If you use foreach loop then you will see the empty strings in the elements of substrings array.
internal class Program
{
// Below is the method that will delete all whitespaces and unite the string broken into substrings.
public static string RemoveSpecifiedChars (string input, char [] delimiters)
{
string[] substrings = input.Split(delimiters);
string output = string.Empty;
foreach (string substring in substrings)
{
output = string.Concat(output, substring);
}
return output;
}
static void Main(string[] args)
{
string s1 = " this is a\nstring! And \t\t this is not. ";
Console.WriteLine("This is how string looks before: " s);
char[] delimiters = { ' ', '\n', '\t' };
string s2 = removeWhitespaces(s, delimiters);
Console.WriteLine("\nThis is how string looks after: " s1);
Console.WriteLine("\nPress any key to terminate the program. ");
Console.Read();
}
}
Here is the output:
This is how string looks before: this is a
string! And this is not.
This is how string looks after: thisisastring!Andthisisnot.
Please don't get me wrong. There are many explanations and I read the official documents but still it explains nothing to me regards to method I showed above. Thanks in advance for any answers!
CodePudding user response:
string.Split()
method:
" ".Split();
will result in an array with 2 string.Empty
items as there is nothing (empty) on either side of the space character.
" something".Split();
and "something ".Split();
will result in an array with two items, that one of them is an empty string, and actually one side of the space character is empty.
"a b".Split(); //double space in between
The first space has a
on the left side and an empty string on the right side (the right side is empty because there is another delimiter right after), the second space, has an empty string on the left side and b
on the right side. so the result will be:
{"a","","","b"}