我在分割字符串时遇到问题。如何拆分不同字符之间的字符串
我想仅分割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
。
您可以使用它任意数量的你想要的。
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];
请注意,我使用的过载和正在采取的秒项目来自返回的数组。
但是,正如@Guffa在his answer中指出的那样,您所做的并不是真正的分割,而是提取特定的子字符串,因此使用他的方法可能会更好。
这根本不是什么分割,所以使用Split
会创建一堆你不想使用的字符串。简单地获得字符的索引,并使用SubString
:
int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
使用此代码
var varable = text.Split(':', '#')[1];
这是否帮助:
[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);
注:这也将赶上不是在问题中指定的顺序字符之间的字符串,例如'is'在'“这是##A:测试# 。“' – Guffa 2013-02-11 13:44:31