我有这个字符串:
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)
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)
您可以使用该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)
阅读本文:http://www.dotnetperls.com/split ,解决方案可能是这样的:
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)
有一个版本string.Split
需要一个字符串数组和一个StringSplitOptions
参数:
http://msdn.microsoft.com/zh-CN/library/tabh47cf.aspx