Difference between revisions of "Split a string"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
 
Line 14: Line 14:
  
 
<syntaxhighlight lang=csharp line>
 
<syntaxhighlight lang=csharp line>
Console.WriteLine("Comma separated strings");
+
Console.WriteLine("Space separated strings");
 
// String of Vowels
 
// String of Vowels
 
string names = "Andy Erica Ian Oliver Ursula";
 
string names = "Andy Erica Ian Oliver Ursula";

Latest revision as of 10:07, 20 May 2024

You can take a string and split it using a separating character:

1 Console.WriteLine("Comma separated strings");
2 // String of Vowels
3 string vowels = "A,E,I,O,U";
4 // Split vowels separated by a comma followed by space
5 string[] VowelList = vowels.Split(",");
6 foreach (string v in VowelsList)
7   Console.WriteLine(v);

You can use any separating character:

1 Console.WriteLine("Space separated strings");
2 // String of Vowels
3 string names = "Andy Erica Ian Oliver Ursula";
4 // Split vowels separated by a comma followed by space
5 string[] NamelList = names.Split(" ");
6 foreach (string n in NameList)
7   Console.WriteLine(n);