我遇到了字符串分割的问题。我只想在两个不同的字符之间分割单词:
string text = "the dog :is very# cute";
我该如何仅获取位于冒号和井号字符之间的单词 is very ?
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);
这里有一个演示
。
您可以使用它任意次数。
这实际上并不是一个真正的拆分,所以使用 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
的重载之一接受params char[]
- 您可以使用任意数量的字符进行拆分:string isVery = 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);
我会使用string.Split两次。首先获取第一个分隔符右边的字符串,然后使用此结果获取第二个分隔符左边的字符串。
string text = "the dog :is very# cute";
string result = text.Split(":")[1] // is very# cute";
.Split("#")[0]; // is very
这样做可以避免在索引和正则表达式上玩耍,我认为这样更易读。