首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >String.Split()、空字符串和删除指定字符的方法

String.Split()、空字符串和删除指定字符的方法
EN

Stack Overflow用户
提问于 2022-04-09 10:07:16
回答 1查看 202关注 0票数 1

我的目标是制作一个非常简单的程序,它将删除指定的字符,从而联合一些字符串。您可以看到下面的代码。分隔符是:空格、\n和\t。实际上困扰我的是,Split()方法在看到字符串的要领和结尾处的分隔符字符时给出了String.Empty,或者如果它看到分隔符两次(例如,两个连续的空格),它也会给出String.Empty()。我确信它们是一个很好的原因,我对此并不完全理解,但困扰我的是,下面的程序在RemoveSpecifiedCharacters方法的帮助下如何正确地忽略(看起来像是“删除”它们,但实际上它只是忽略了它们)这个空字符串(特别是两个\t\t),它像空格一样将所有字符串从子字符串数组连接到一个名为s2的新字符串中?如果您使用foreach循环,那么您将在子字符串数组的元素中看到空字符串。

代码语言:javascript
运行
复制
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();
        }
    }

这是输出:

代码语言:javascript
运行
复制
This is how string looks before:  this is a
string! And              this is not.

This is how string looks after: thisisastring!Andthisisnot.

请不要误解我的意思。有许多解释,我看了官方文件,但它仍然没有向我解释关于我上面显示的方法。预先感谢您的任何回答!

EN

Stack Overflow用户

回答已采纳

发布于 2022-04-09 10:18:30

string.Split()方法:

" ".Split();将产生一个包含2个string.Empty项的数组,因为在空格字符的任何一侧都没有(空)。

" something".Split();"something ".Split();将产生一个包含两个项的数组,其中一个是空字符串,而实际上是空字符的一侧。

代码语言:javascript
运行
复制
"a  b".Split(); //double space in between

第一个空格的左边是a,右边是空字符串(右侧是空的,因为后面有另一个分隔符),第二个空格的左边是空字符串,右边是b。其结果将是:

代码语言:javascript
运行
复制
{"a","","","b"}
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71807057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档