Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用字符串分隔符拆分字符串?_C#_String_Split - Fatal编程技术网

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

C# 如何使用字符串分隔符拆分字符串?,c#,string,split,C#,String,Split,我有这个字符串: My name is Marco and I'm from Italy 我想分割它,分隔符是Marco和,所以我应该得到一个带有 我的名字在[0]和 我来自意大利at[1] 我怎样才能用C#来做呢 我试过: .Split("is Marco and") 但是它只需要一个字符。您可以使用IndexOf方法获取字符串的位置,并使用该位置和搜索字符串的长度将其拆分 也可以使用正则表达式。一个简单的例子证明了这一点 using System; using System.Tex

我有这个字符串:

My name is Marco and I'm from Italy
我想分割它,分隔符
是Marco和
,所以我应该得到一个带有

  • 我的名字
    在[0]和
  • 我来自意大利
    at[1]
我怎样才能用C#来做呢

我试过:

.Split("is Marco and")

但是它只需要一个字符。

您可以使用
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);
    }
  }
}

考虑
周围的空间是Marco和
。是要在结果中包含空格,还是要将其删除?很可能您想使用“
”is Marco和“
作为分隔符…

有一个版本的
字符串。Split
采用字符串数组和一个
StringSplitOptions
参数:

如果您有一个单字符分隔符(例如
),则可以将其减少为(请注意单引号):

试试看


您正在相当复杂的子字符串上拆分字符串。我会使用正则表达式而不是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");
阅读后,解决方案可以是:

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

不,它需要一个字符串数组。您可以删除
string
.Split(new[]{”是Marco,“},StringSplitOptions.None)
new string[]
是多余的。在这种情况下,您可以使用
new[]
注意str.Split(',')中的单引号;而不是str.Split(“,”);我花了一段时间才明白notice@user3656612因为它接受字符(char),而不是字符串。字符被单引号包围。我不明白为什么它们在C#中包含string.split(字符)而不是string.split(字符串)。。。我的意思是既有string.split(char[])又有string.split(string[])!相关的
string[] tokens = str.Split(',');
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);
var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);