我的目标是制作一个非常简单的程序,它将删除指定的字符,从而联合一些字符串。您可以看到下面的代码。分隔符是:空格、\n和\t。实际上困扰我的是,Split()方法在看到字符串的要领和结尾处的分隔符字符时给出了String.Empty,或者如果它看到分隔符两次(例如,两个连续的空格),它也会给出String.Empty()。我确信它们是一个很好的原因,我对此并不完全理解,但困扰我的是,下面的程序在RemoveSpecifiedCharacters方法的帮助下如何正确地忽略(看起来像是“删除”它们,但实际上它只是忽略了它们)这个空字符串(特别是两个\t\t),它像空格一样将所有字符串从子字符串数组连接到一个名为s2的新字符串中?如果您使用foreach循环,那么您将在子字符串数组的元素中看到空字符串。
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();
}
}
这是输出:
This is how string looks before: this is a
string! And this is not.
This is how string looks after: thisisastring!Andthisisnot.
请不要误解我的意思。有许多解释,我看了官方文件,但它仍然没有向我解释关于我上面显示的方法。预先感谢您的任何回答!
发布于 2022-04-09 10:18:30
string.Split()
方法:
" ".Split();
将产生一个包含2个string.Empty
项的数组,因为在空格字符的任何一侧都没有(空)。
" something".Split();
和"something ".Split();
将产生一个包含两个项的数组,其中一个是空字符串,而实际上是空字符的一侧。
"a b".Split(); //double space in between
第一个空格的左边是a
,右边是空字符串(右侧是空的,因为后面有另一个分隔符),第二个空格的左边是空字符串,右边是b
。其结果将是:
{"a","","","b"}
https://stackoverflow.com/questions/71807057
复制相似问题