tags:

views:

162

answers:

6

I have a string "pc1|pc2|pc3|"

I want to get each word on different line like:

pc1

pc2

pc3

I need to do this in C#...

any suggestions??

+12  A: 
 string[] parts = s.Split(new [] {'|'}, StringSplitOptions.RemoveEmptyEntries);

 foreach (string part in parts)
    Console.WriteLine(part);
Philippe Leybaert
and then foreach (string pc in parts) {Console.WriteLine(pc);}
PoweRoy
split should be capitalized "Split"
Dave
Note that with your example, you will get an empty string as the last part, because there is nothing after the last |.
Meta-Knight
Thanks for the corrections. I added "RemoveEmptyEntries" to avoid the empty part at the end
Philippe Leybaert
This doesn't compile. There is no such overload. Use a char array as the separator parameter.
bruno conde
+1  A: 
string s = "pc1|pc2|pc3|";
string[] words = s.Split('|');
Bryan McLemore
A: 
string words[] = string.Split("|");
foreach (string word in words)
{
  Console.WriteLine(word);
}
mculp
your variable is shadowing the built-in not normally a good practice even in throwaway answer code ;)
Bryan McLemore
A: 
string fullString = "pc1|pc2|pc3|";
foreach (string pc in fullString.Split('|'))
   Console.WriteLine(pc);
Jon
split should be capitalized "Split"
Dave
Thanks! I made the change.
Jon
+4  A: 
string withNewLines = original.Replace("|", Environment.NewLine);
LukeH
+4  A: 
var parts = s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

foreach (string word in parts)
{
  Console.WriteLine(word);
}
bruno conde
Either put a `var` or a `string[]` as variable type of `parts`
Alex Bagnolini