How do I split a string?
Category: System, viewed: 1327 time(s).
This example demonstrate how to split a csv (comma separated value) string. The String.Split() returns the splitted data as an array of string.
using System;
namespace Kodecsharp.Example.System
{
public class StringSplit
{
public static void Main(string[] args)
{
string row = "0001,Foo,Bar,California Bay,1976";
//
// Returns a string array that contains the substrings in this
// instance that are delimited by elements of a specified
// Unicode character array.
//
string[] fields = row.Split(',');
foreach (string field in fields)
{
Console.WriteLine(field);
}
row = "The quick,brown:fox;jumps over the lazy dog";
char[] delimiters = { ' ', ',', ':' };
//
// Returns a string array that contains the substrings in this
// instance that are delimited by elements of a specified Unicode
// character array. A parameter specifies the maximum number of
// substrings to return.
//
fields = row.Split(delimiters, 6);
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
}
}
The result of our code can be seen below.
0001
Foo
Bar
California Bay
1976
The
quick
brown
fox;jumps
over
the lazy dog
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!