如何使用c#中的多字符分隔符分割字符串?

时间:2022-04-08 22:07:27

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

如果我想用一个单词分隔符来分割字符串呢?

For example, This is a sentence.

例如,这是一个句子。

I want to split on is and get This and a sentence.

我想把这个和一个句子分开。

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

在Java中,我可以以分隔符的形式发送字符串,但是如何在c#中实现这一点呢?

10 个解决方案

#1


261  

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

#2


51  

You can use the Regex.Split method, something like this:

您可以使用Regex。拆分法,大概是这样的:

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.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.

编辑:这满足你给出的例子。注意一个普通的字符串。Split将在“This”结尾的“is”上进行拆分,因此我使用Regex方法并将单词边界包含在“is”中。但是,请注意,如果您只是在错误中编写了这个示例,那么请使用String。分裂可能足够了。

#3


29  

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


    }
}

#4


25  

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 only want the word "is" removed from the sentence and the word "this" to remain intact.

编辑:“is”被填充在数组的两边,以保持你只希望单词“is”从句子中删除,单词“this”保持完整。

#5


4  

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。在该字符上分割以分割结果字符串以获得相同的效果。

#6


4  

...In short:

…简而言之:

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

#7


3  

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

或使用这段代码;(同样:新字符串[])

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

#8


0  

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="to=xxx@gmail.com=yyy@yahoo.co.in";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1]=xxx@gmail.com=yyy@yahoo.co.in

#9


0  

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

#10


-5  

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

#1


261  

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

#2


51  

You can use the Regex.Split method, something like this:

您可以使用Regex。拆分法,大概是这样的:

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.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.

编辑:这满足你给出的例子。注意一个普通的字符串。Split将在“This”结尾的“is”上进行拆分,因此我使用Regex方法并将单词边界包含在“is”中。但是,请注意,如果您只是在错误中编写了这个示例,那么请使用String。分裂可能足够了。

#3


29  

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


    }
}

#4


25  

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 only want the word "is" removed from the sentence and the word "this" to remain intact.

编辑:“is”被填充在数组的两边,以保持你只希望单词“is”从句子中删除,单词“this”保持完整。

#5


4  

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。在该字符上分割以分割结果字符串以获得相同的效果。

#6


4  

...In short:

…简而言之:

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

#7


3  

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

或使用这段代码;(同样:新字符串[])

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

#8


0  

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="to=xxx@gmail.com=yyy@yahoo.co.in";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1]=xxx@gmail.com=yyy@yahoo.co.in

#9


0  

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

#10


-5  

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