文字列を分割するのに問題があります。単語だけを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
です。
何回でも使えます。
これは実際には分割ではないため、を使用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);
のオーバーロードの1つは、string.Split
次params char[]
のように分割するために任意の数の文字を使用できます。
string isVery = text.Split(':', '#')[1];
そのオーバーロードを使用していて、返された配列から2番目の項目を取得していることに注意してください。
ただし、@ Guffaが彼の回答で述べているように、あなたがしていることは実際には分割ではなく、特定のサブ文字列を抽出することなので、彼のアプローチを使用する方が良いかもしれません。
使用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);
これは役に立ちますか:
[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]);
}