Employers - Post Free Jobs
Forum guidelines
AuthorQuestion
Get a substring
Posted on: 07 Jan 2014

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.


AuthorReply
Vulpes
  • 1
  • 0
accepted
Re: Get a substring
Posted on: 07 Jan 2014   Accepted Answer
Unfortunately, it doesn't compile.

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.




Re: Get a substring
Posted on: 07 Jan 2014  
If 's' is your string, then this is perhaps the easiest way:

string defg = s.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1];



Re: Get a substring
Posted on: 07 Jan 2014  
Another easy way using regular expressions:

using System.Text.RegularExpressions;

// ...

string defg2 = Regex.Match(s, @"\s+(\S+)\s+").Groups[1].Value; 


Dave
  • 0
  • 0
Re: Get a substring
Posted on: 07 Jan 2014  
Interesting. Can you explain new char[]{' '}? Is this represents spaces in any length?
Re: Get a substring
Posted on: 07 Jan 2014  
No, it's a char array containing a single space.

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.



Dave
  • 0
  • 0
Re: Get a substring
Posted on: 07 Jan 2014  
Thank you very much.
Why not use
string defg = s.Split(" ", StringSplitOptions.RemoveEmptyEntries)[1];

Dave
  • 0
  • 0
Re: Get a substring
Posted on: 07 Jan 2014  
Thank you for your helps!!
Employers - Post Free Jobs

SPONSORED BY

Offshore Software and Database Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.