Hi,
I got a string something like
"abc-----defg---hi"
Any simple way to get the substring "defg"?
Note, "---" represents spaces and I don't know the length.
Hi,
I got a string something like
"abc-----defg---hi"
Any simple way to get the substring "defg"?
Note, "---" represents spaces and I don't know the length.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jan 7, 2014, 6:14 PM
The first argument has to be either a char or string array if you're using StringSplitOptions.
So this works:
string defg = s.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1];
and so does this:
string defg = s.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries)[1];
If you're not using StringSplitOptions, then the first argument has to be a char array but with an important difference - it's a 'params' array. So you can pass a single char such as ' ' or several single chars rather than an array.
DavePosted Jan 7, 2014, 9:02 PM
DavePosted Jan 7, 2014, 5:47 PM
Why not use
string defg = s.Split(" ", StringSplitOptions.RemoveEmptyEntries)[1];
VulpesPosted Jan 7, 2014, 1:37 PM
The idea is that you split the string using a single space as the separator. Where there are multiple spaces adjacent to each other, this will result in empty strings being added to the resulting array. However, by specifying StringSplitOptions.RemoveEmptyEntries, we get rid of these empty strings which just leaves us with 3 strings 'abc', 'defg' and 'hi'.
The one we want is the second one which, of course, has an index of 1 in the array.
DavePosted Jan 7, 2014, 1:15 PM
VulpesPosted Jan 7, 2014, 12:58 PM
using System.Text.RegularExpressions;
// ...
string defg2 = Regex.Match(s, @"\s+(\S+)\s+").Groups[1].Value;
VulpesPosted Jan 7, 2014, 12:52 PM
string defg = s.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1];