如何使用字符串分隔符拆分字符串?

mar*_*zzz 240 c# string split

我有这个字符串:

My name is Marco and I'm from Italy
Run Code Online (Sandbox Code Playgroud)

我想用分隔符拆分它is Marco and,所以我应该得到一个数组

  • My name 在[0]和
  • I'm from Italy 在[1].

我怎么能用C#做到这一点?

试过

.Split("is Marco and")
Run Code Online (Sandbox Code Playgroud)

但它只想要一个字符.

jue*_*n d 492

string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)

如果你有一个字符分隔符(例如,),你可以减少它(注意单引号):

string[] tokens = str.Split(',');
Run Code Online (Sandbox Code Playgroud)

  • 我不明白为什么他们在C#中包含了string.split(char)而不是string.split(string)...我的意思是有string.split(char [])和string.split(string [] )! (18认同)
  • 注意str.Split中的单引号(','); 而不是str.Split(","); 我花了一段时间才注意到 (6认同)
  • 在这种情况下,`new string []`是多余的,你可以使用`new []` (5认同)
  • @ user3656612因为它接受字符(char),而不是字符串.字符被单引号括起来. (2认同)

And*_*lad 28

.Split(new string[] { "is Marco and" }, StringSplitOptions.None)
Run Code Online (Sandbox Code Playgroud)

考虑周围的空间"is Marco and".您想在结果中包含空格,还是要删除它们?您很可能想要" is Marco and "用作分隔符......


Huu*_*som 18

您正在一个相当复杂的子字符串上拆分字符串.我使用正则表达式而不是String.Split.后者更适用于对文本进行标记.

例如:

var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");
Run Code Online (Sandbox Code Playgroud)


Dan*_*Man 12

请尝试此功能.

string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 9

您可以使用该IndexOf方法获取字符串的位置,并使用该位置和搜索字符串的长度将其拆分.


您还可以使用正则表达式.一个简单的谷歌搜索结果与此相关

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {
        Console.WriteLine(line);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Gui*_*shy 7

阅读本文:http://www.dotnetperls.com/split ,解决方案可能是这样的:

var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)


Cha*_*ert 5

有一个版本string.Split需要一个字符串数组和一个StringSplitOptions参数:

http://msdn.microsoft.com/zh-CN/library/tabh47cf.aspx