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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jan 7, 2014, 1:14 PM EST
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.
VulpesRank #55 · 29.2K reputationPosted Jan 7, 2014, 7:52 AM EST
string defg = s.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1];
VulpesRank #55 · 29.2K reputationPosted Jan 7, 2014, 7:58 AM EST
using System.Text.RegularExpressions;
// ...
string defg2 = Regex.Match(s, @"\s+(\S+)\s+").Groups[1].Value;
Dave48 reputationPosted Jan 7, 2014, 8:15 AM EST
VulpesRank #55 · 29.2K reputationPosted Jan 7, 2014, 8:37 AM EST
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.
Dave48 reputationPosted Jan 7, 2014, 12:47 PM EST
Why not use
string defg = s.Split(" ", StringSplitOptions.RemoveEmptyEntries)[1];
Dave48 reputationPosted Jan 7, 2014, 4:02 PM EST