如何通过 C# 中的多字符分隔符拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1126915/
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 08:49:33  来源:igfitidea点击:

How do I split a string by a multi-character delimiter in C#?

c#.netstring

提问by Saobi

What if I want to split a string using a delimiter that is a word?

如果我想使用作为单词的分隔符拆分字符串怎么办?

For example, This is a sentence.

例如,This is a sentence

I want to split on isand get Thisand a sentence.

我想拆分is并获得Thisa sentence

In Java, I can send in a string as a delimiter, but how do I accomplish this in C#?

在 中Java,我可以发送一个字符串作为分隔符,但是如何在 中完成此操作C#

采纳答案by bruno conde

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

Example from the docs:

文档中的示例:

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;

// ...
result = source.Split(stringSeparators, StringSplitOptions.None);

foreach (string s in result)
{
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}

回答by IRBMe

You can use the Regex.Splitmethod, something like this:

您可以使用Regex.Split方法,如下所示:

Regex regex = new Regex(@"\bis\b");
string[] substrings = regex.Split("This is a sentence");

foreach (string match in substrings)
{
   Console.WriteLine("'{0}'", match);
}

Edit: This satisfies the example you gave. Note that an ordinary String.Splitwill also split on the "is" at the end of the word "This", hence why I used the Regexmethod and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Splitwill probably suffice.

编辑:这满足你给出的例子。请注意,普通的String.Split也会在单词“This”末尾的“ is”上拆分,因此我使用了Regex方法并在“ is”周围包含了单词边界。但是请注意,如果您只是错误地编写了这个示例,那么String.Split可能就足够了。

回答by Paul Sonier

You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.

您可以使用 String.Replace() 将所需的拆分字符串替换为字符串中未出现的字符,然后在该字符上使用 String.Split 以拆分结果字符串以达到相同的效果。

回答by ahawker

string s = "This is a sentence.";
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None);

for(int i=0; i<res.length; i++)
    Console.Write(res[i]);

EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you onlywant the word "is" removed from the sentence and the word "this" to remain intact.

编辑:“is”在数组的两边都填充了空格,以保留这样一个事实,即您希望从句子中删除“is”这个词,而“this”这个词保持不变。

回答by Susmeet Khaire

string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

回答by eka808

Based on existing responses on this post, this simplify the implementation :)

根据这篇文章的现有回复,这简化了实现:)

namespace System
{
    public static class BaseTypesExtensions
    {
        /// <summary>
        /// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string[] Split(this string s, string separator)
        {
            return s.Split(new string[] { separator }, StringSplitOptions.None);
        }


    }
}

回答by ParPar

...In short:

...简而言之:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);

回答by Prabu

var dict = File.ReadLines("test.txt")
               .Where(line => !string.IsNullOrWhitespace(line))
               .Select(line => line.Split(new char[] { '=' }, 2, 0))
               .ToDictionary(parts => parts[0], parts => parts[1]);


or 

    enter code here

line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1][email protected][email protected]

回答by Cagdas

Or use this code; ( same : new String[] )

或使用此代码;(相同: new String[] )

.Split(new[] { "Test Test" }, StringSplitOptions.None)

回答by SteveD

Here is an extension function to do the split with a string separator:

这是一个使用字符串分隔符进行拆分的扩展函数:

public static string[] Split(this string value, string seperator)
{
    return value.Split(new string[] { seperator }, StringSplitOptions.None);
}

Example of usage:

用法示例:

string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");