【发布时间】:2013-02-10 12:12:51
【问题描述】:
我在拆分字符串时遇到问题。我只想在 2 个不同的字符之间拆分单词:
string text = "the dog :is very# cute";
我怎样才能只抓住: 和# 字符之间的词,非常?
【问题讨论】:
我在拆分字符串时遇到问题。我只想在 2 个不同的字符之间拆分单词:
string text = "the dog :is very# cute";
我怎样才能只抓住: 和# 字符之间的词,非常?
【问题讨论】:
您可以将String.Split() 方法与params char[] 一起使用;
返回一个字符串数组,其中包含此实例中的子字符串 由指定 Unicode 字符数组的元素分隔。
string text = "the dog :is very# cute";
string str = text.Split(':', '#')[1]; // [1] means it selects second part of your what you split parts of your string. (Zero based)
Console.WriteLine(str);
这是DEMO。
您可以随意使用它。
【讨论】:
"This #is# a :test#."中的is
这根本不是真正的拆分,因此使用Split 会创建一堆您不想使用的字符串。只需获取字符的索引,然后使用SubString:
int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
【讨论】:
使用此代码
var varable = text.Split(':', '#')[1];
【讨论】:
Regex regex = new Regex(":(.+?)#");
Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value);
【讨论】:
string.Split 中的一个overloads 采用params char[] - 您可以使用任意数量的字符进行拆分:
string isVery = text.Split(':', '#')[1];
请注意,我正在使用该重载并从返回的数组中获取 second 项。
但是,正如@Guffa 在his answer 中指出的那样,您所做的并不是真正的拆分,而是提取特定的子字符串,因此使用他的方法可能会更好。
【讨论】:
这有帮助吗:
[Test]
public void split()
{
string text = "the dog :is very# cute" ;
// how can i grab only the words:"is very" using the (: #) chars.
var actual = text.Split(new [] {':', '#'});
Assert.AreEqual("is very", actual[1]);
}
【讨论】:
使用String.IndexOf 和String.Substring
string text = "the dog :is very# cute" ;
int colon = text.IndexOf(':') + 1;
int hash = text.IndexOf('#', colon);
string result = text.Substring(colon , hash - colon);
【讨论】:
我只会使用string.Split 两次。获取第一个分隔符右侧的字符串。然后,使用结果,获取第二个分隔符左侧的字符串。
string text = "the dog :is very# cute";
string result = text.Split(":")[1] // is very# cute";
.Split("#")[0]; // is very
它避免了使用索引和正则表达式,这使得 IMO 更具可读性。
【讨论】: