C# 字符串分割:如何分割连续超过2个空格
"C# 字符串分割:如何分割连续超过2个空格"\n\n您可以使用正则表达式来分割连续超过2个空格的字符串。下面是一个使用 C# 的示例代码:\n\ncsharp\nusing System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n public static void Main()\n {\n string input = \"Hello World! This is a test.\";\n string pattern = @\"\s{2,}\" ; // 匹配连续超过2个空格\n\n string[] result = Regex.Split(input, pattern);\n\n foreach (string s in result)\n {\n Console.WriteLine(s);\n }\n }\n}\n\n\n输出结果为:\n\n\nHello\nWorld!\nThis is a test.\n\n\n在代码中,我们首先定义了一个输入字符串 input,其中包含连续超过2个空格的情况。然后,我们使用正则表达式模式 @"\s{2,}\" 来匹配连续超过2个空格。最后,我们调用 Regex.Split 方法,并将输入字符串和正则表达式模式作为参数传递给它。该方法会返回一个字符串数组,其中每个元素都是根据正则表达式模式进行分割后的结果。\n\n在循环中,我们遍历数组并打印每个元素。输出结果显示字符串已经成功分割,连续超过2个空格的部分被正确处理。
原文地址: https://www.cveoy.top/t/topic/psMV 著作权归作者所有。请勿转载和采集!