20

Possible Duplicate:
Best way to specify whitespace in a String.Split operation

I am trying to read in the hosts file that contains:

127.0.0.1 localhost
ect...

So as I read it in line by line I need to grab the IP and the host name but how would I grab them if they are formated by any number of tabs or spaces or both.

127.0.0.1<tab><space>localhost
127.0.0.1<space>localhost
127.0.0.1<space><space><space><space>localhost
Community
  • 1
  • 1
user622469
  • 453
  • 1
  • 3
  • 14
  • Just read the entire line until a return character. Once you have entire line break it up into two strings one which contains `XXX.XXX.XXX.XXX[whitespace]........alpha characters` – Security Hound Jun 21 '12 at 16:51
  • 1
    I think people jumped the gun in marking this as a duplicate. The linked question isn't quite the same as this question, and the accepted answer there doesn't do the right thing – Jezzamon Oct 02 '15 at 06:08

1 Answers1

37
var components = host.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167
  • can we use above somehow to include whitespaces and other character like a , ? – Muds Jan 29 '18 at 17:20
  • @Muds Sure. Explicitly specify the desired separators in the first argument. – Branko Dimitrijevic Jan 31 '18 at 14:17
  • thanks for replying, i did try to do but it isnt accepting it as correct format – Muds Jan 31 '18 at 15:17
  • @Muds What did you try, and what error did you get? – Branko Dimitrijevic Feb 01 '18 at 07:23
  • host.Split('a','b',(char)null); – Muds Feb 05 '18 at 16:54
  • @Muds The first argument is an array, so you'll need to do something like this: `host.Split(new [] {'a', 'b'}, StringSplitOptions.RemoveEmptyEntries)`. Or you can just do this if you don' care about removing empty components: `host.Split('a', 'b')` - which works because this overload uses `params`. – Branko Dimitrijevic Feb 06 '18 at 08:00
  • branko, i intended to split on a, b and any white space, hence was willing to pass a null, removing empty entries wont serve the purpose – Muds Feb 07 '18 at 09:23
  • @Muds And as I said: _"Explicitly specify the desired separators in the first argument."_. I don't think you can combine non-space and space separators like you attempted - you'll have to explicitly list the whitespaces (and non-whitespaces) you are interested in (the full list of whitespaces is here: [Char.IsWhiteSpace](https://learn.microsoft.com/en-us/dotnet/api/system.char.iswhitespace)), or implement your own method that makes use of `Char.IsWhiteSpace`. – Branko Dimitrijevic Feb 07 '18 at 12:40
  • split(null) of split(char[0]) works hence i was just wondering if we could just cast null to char and use it but doesnt seem to be right option as for now – Muds Feb 07 '18 at 13:30