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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1000831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:14:39  来源:igfitidea点击:

How can i split the string only once using C#

c#

提问by

Example : a - b - c must be split as a and b - c, instead of 3 substrings

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

回答by Guffa

Specify the maximum number of items that you want:

指定所需的最大项目数:

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

回答by AgileJon

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

回答by Fenton

You could use indexOf() to find the first instance of the character you want to split with, then substring() to get the two aspects. For example...

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

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.

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

回答by tanascius

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

回答by Matthew Flaschen

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

回答by SLaks

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

回答by Gaurav Aroraa

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