2013-02-10 111 views
8

我在分割字符串時遇到問題。如何拆分不同字符之間的字符串

我想僅分割2個不同字符之間的單詞。我有這個文本:

string text = "the dog :is very# cute" ; 

我如何只抓住單詞:「非常」使用(:#)字符。

回答

9

您可以使用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

您可以使用它任意數量的你想要的。

+2

注:這也將趕上不是在問題中指定的順序字符之間的字符串,例如'is'在'「這是##A:測試# 。「' – Guffa 2013-02-11 13:44:31

2
Regex regex = new Regex(":(.+?)#"); 
Console.WriteLine(regex.Match("the dog :is very# cute").Groups[1].Value); 
3

一個string.Splitoverloads的需要params char[] - 你可以使用任何數目的字符分割上:

string isVery = text.Split(':', '#')[1]; 

請注意,我使用的過載和正在採取的項目來自返回的數組。

但是,正如@Guffa在his answer中指出的那樣,您所做的並不是真正的分割,而是提取特定的子字符串,因此使用他的方法可能會更好。

10

這根本不是什麼分割,所以使用Split會創建一堆你不想使用的字符串。簡單地獲得字符的索引,並使用SubString

int startIndex = text.IndexOf(':'); 
int endIndex = test.IndexOf('#', startIndex); 
string very = text.SubString(startIndex, endIndex - startIndex - 1); 
4

使用此代碼

var varable = text.Split(':', '#')[1]; 
2

這是否幫助:

[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]); 
    } 
2

使用String.IndexOfString.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);