如何在 C# 中拆分单词而不是字符

How to Split at word not at a char in c#

如何在单词而不是字符处拆分字符串,例如 我想将这个字符串拆分成一个字符串数组:

Hello /*End*/ World /*End*/ Bye /*End*/ live /*End*/

我想在 /*End*/ 拆分 所以数组会像这样

{Hello,World,Bye,live}

有什么建议吗?

您可以为此使用正则表达式 class:(来自 System.Text.RegularExpressions 命名空间)

string[] Result = Regex.Split(Input, "end");

它会为您提供一个按您指定的模式拆分的字符串数组。

有一个重载 Split 函数,它接受一个字符串数组,您只能提供 1 个字符串,如下所示。

string input = "Hello /End/ World /End/ Bye /End/ live /End/ ";
var output = input.Split(new[] { "/*End*/" }, StringSplitOptions.None);

使用 string.Split(string[], StringSplitOptions) 重载。

var parts = str.Split(new[] {@"/*End*/"}, StringSplitOptions.None)

试试正则表达式

  string input = "Hello /*End*/ World /*End*/ Bye /*End*/ live /*End*/";
  string pattern = "/*End*/";            // Split on hyphens 

  string[] substrings = Regex.Split(input, pattern);
        var str = @"Hello /End/ World /End/ Bye /End/ live /End/ ";

        var words = str.Split(new string[] { "/End/" }, System.StringSplitOptions.None);

        foreach(var word in words)
        {
            Console.WriteLine(word);    
        }

简单的正则表达式模式:

\/\*End\*\/

see demo