例子:a - b - c 应该拆分成 a 和 b - c,而不是 3 个子字符串。
例子:a - b - c 应该拆分成 a 和 b - c,而不是 3 个子字符串。
指定您想要的最大项目数量:
string[] splitted = text.Split(new string[]{" - "}, 2, StringSplitOptions.None);
string s = "a - b - c";
string[] parts = s.Split(new char[] { '-' }, 2);
// note, you'll still need to trim off any whitespace
"a-b-c".Split( new char[] { '-' }, 2 );
int pos = myString.IndexOf('-');
string first = myString.Substring(0, pos);
string second = myString.Substring(pos);
这只是一个粗略的例子 - 如果你不想在其中包含分隔符,你需要进行调整 - 但你应该可以从中得到灵感。
string[] splitted = "a - b - c".Split(new char[]{' ', '-'}, 2, StringSplitOptions.RemoveEmptyEntries);
var str = "a-b-c";
int splitPos = str.IndexOf('-');
string[] split = { str.Remove(splitPos), str.Substring(splitPos + 1) };
我加入比较晚,上面的许多答案都已经与我的想法相匹配:
字符串有它自己的
Split
你可以使用它来找到解决方案,以下是针对你问题的示例:
using System;
public class Program
{
public static void Main()
{
var PrimaryString = "a - b - c";
var strPrimary = PrimaryString.Split( new char[] { '-' }, 2 );
Console.WriteLine("First:{0}, Second:{1}",strPrimary[0],strPrimary[1]);
}
}
Output:
First:a , Second: b - c
[a,b,c]
而不是 [a,b-c]
的数组。另外,语言错误。 - Jamie Rees