如何使用C#将字符串拆分一次

时间:2009-06-16 11:14:07

标签: c#

示例:a - b - c必须拆分为 a和b - c,而不是3个子串

8 个答案:

答案 0 :(得分:20)

指定所需的最大项目数:

string[] splitted = text.Split(new string[]{" - "}, 2, StringSplitOptions.None);

答案 1 :(得分:13)

string s = "a - b - c";
string[] parts = s.Split(new char[] { '-' }, 2);
// note, you'll still need to trim off any whitespace

答案 2 :(得分:4)

"a-b-c".Split( new char[] { '-' }, 2 );

答案 3 :(得分:2)

您可以使用indexOf()来查找要分割的字符的第一个实例,然后使用substring()来获取这两个方面。例如......

int pos = myString.IndexOf('-');
string first = myString.Substring(0, pos);
string second = myString.Substring(pos);

这是一个粗略的例子 - 如果你不想在那里使用分隔符,你需要使用它 - 但你应该从中得到这个想法。

答案 4 :(得分:1)

string[] splitted = "a - b - c".Split(new char[]{' ', '-'}, 2, StringSplitOptions.RemoveEmptyEntries);

答案 5 :(得分:0)

var str = "a-b-c";
int splitPos = str.IndexOf('-');
string[] split = { str.Remove(splitPos), str.Substring(splitPos + 1) };

答案 6 :(得分:0)

我加入的很晚,上面的许多答案与我的以下词语相符:

字符串有自己的

  

分割

您可以使用相同的方法来查找问题的解决方案,以下是您的问题的示例:

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

答案 7 :(得分:-1)

使用Regex.Split()