如果我想使用一个单词的分隔符拆分字符串怎么办?
例如,This is a sentence.
我想分开is并得到This和a sentence.
在Java,我可以发送一个字符串作为分隔符,但我如何实现这一点C#?
bru*_*nde 278
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
来自文档的示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
IRB*_*BMe 55
您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:这满足您给出的示例.请注意,普通的String.Split也会在单词"This"的末尾分成" is ",因此我使用Regex方法并在" is " 周围包含单词边界.但请注意,如果您只是错误地编写了此示例,则String.Split可能就足够了.
eka*_*808 34
根据这篇文章的现有回复,这简化了实施:)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
aha*_*ker 28
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]);
Run Code Online (Sandbox Code Playgroud)
编辑:"是"是为了保护你的事实填补双方在阵列中的空间只需要道"就是"从句子和单词删除"这个"保持不变.
...简而言之:
string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)
或使用此代码;(相同: new String[] )
.Split(new[] { "Test Test" }, StringSplitOptions.None)
Run Code Online (Sandbox Code Playgroud)