如何在不同的字符之间拆分字符串

dar*_*rko 8 c# string split

我在分割字符串时遇到问题.我想只拆分两个不同字符之间的单词:

 string text = "the dog :is very# cute";
Run Code Online (Sandbox Code Playgroud)

我怎样才能抓住唯一的话,是非常,之间:#字符?

Son*_*nül 13

你可以使用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);
Run Code Online (Sandbox Code Playgroud)

这是一个DEMO.

你可以使用任何你想要的数量.

  • 注意:这也会捕获不符合问题中指定顺序的字符之间的字符串,例如``is` in`"This#is #a:test#." (2认同)

Guf*_*ffa 8

这根本不是一个分裂,所以使用Split会创建一堆你不想使用的字符串.只需获取字符的索引,并使用SubString:

int startIndex = text.IndexOf(':');
int endIndex = test.IndexOf('#', startIndex);
string very = text.SubString(startIndex, endIndex - startIndex - 1);
Run Code Online (Sandbox Code Playgroud)


小智 5

使用此代码

var varable = text.Split(':', '#')[1];
Run Code Online (Sandbox Code Playgroud)