If I have various strings that have text followed by whitespace followed by text, how can I parse the substring beginning with the first character in the second block of text?
For example: If I have the string:
"stringA stringB"How can I extract the substring
"stringB"The strings are of various lengths but will all be of the format .
I'm sure this can be easily done with regex but I'm having trouble finding the proper syn开发者_如何学编程tax for c#.
No RegEx needed, just split it.
var test = "stringA stringB";
var second = test.Split()[1];
and if you are in the wonderful LINQ-land
var second = "string1 string2".Split().ElementAtOrDefault(1);
and with RegEx (for completeness)
var str2 = Regex.Match("str1 str2", @"\w (.*$)").Groups[1].Value;
use string.Split()
var test = "stringA stringB";
var elements = test.Split(new[]
{
' '
});
var desiredItem = elements.ElementAtOrDefault(1);
if you want to capture all whitespaces (msdn tells us more):
var test = "stringA stringB";
//var elements = test.Split(); // pseudo overload
var elements = test.Split(null); // correct overload
var desiredItem = elements.ElementAtOrDefault(1);
edit:
why pseudo-overload?
.Split()
gets compiled to.Split(new char[0])
- not documented in MSDN
If all strings are separated by a whitespace you don't need a regex here. You could just use the Split() method:
string[] result = { };
string myStrings = "stringA stringB stringC";
result = myStrings.Split(' ');
You don't need event the Split(). I think a simple IndexOf/Substring will do the job.
var input = "A B";
var result = string.Empty;
var index = input.IndexOf(' ');
if (index >= 0)
{
result = input.Substring(index + 1);
}
精彩评论