简体   繁体   English

我怎样才能使用 C# 将字符串拆分一次

[英]How can i split the string only once using C#

Example: a - b - c must be split as a and b - c, instead of 3 substrings示例:a - b - c 必须拆分为 a 和 b - c,而不是 3 个子字符串

Specify the maximum number of items that you want:指定所需的最大项目数:

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 );

You could use indexOf() to find the first instance of the character you want to split with, then substring() to get the two aspects.您可以使用 indexOf() 来查找要与之拆分的字符的第一个实例,然后使用 substring() 来获取这两个方面。 For example...例如...

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

This is a rough example - you'll need to play with it if you don't want the separator character in there - but you should get the idea from this.这是一个粗略的例子 - 如果你不想在其中使用分隔符,你将需要使用它 - 但你应该从中得到这个想法。

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) };

I have joined late and many of above answers are matched with my following words:我加入晚了,上面的许多答案都与我的以下话相匹配:

string has its own字符串有它自己的

Split分裂

You can use the same to find the solution of your problem, following is the example as per your issue:您可以使用相同的方法来找到问题的解决方案,以下是根据您的问题的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM