[英]How to split string between different chars
我在拆分字符串時遇到問題。 我只想在 2 個不同的字符之間拆分單詞:
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);
這是一個DEMO
。
您可以隨意使用它。
這根本不是真正的拆分,因此使用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];
請注意,我正在使用該重載並從返回的數組中獲取第二項。
但是,正如@Guffa 在他的回答中指出的那樣,您所做的並不是真正的拆分,而是提取特定的子字符串,因此使用他的方法可能會更好。
這是否有幫助:
[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 中更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.