- การใช้ Split แบบปกติ
- การใช้ Split แบบกำหนดจำนวนผลลัพธ์ที่ต้องการ
- การใช้ Split ด้วย multiple separator characters
- การใช้ Split ด้วย string
- Split string based on the first occurrence of the character
- How to: Parse Strings Using String.Split (C# Guide)
1.การใช้ Split แบบปกติ
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string myString = "101,a,b,c,d";
string[] items = myString.Split(',' );
// [0] = "101"
// [1] = "a"
// [2] = "b"
// [3] = "c"
// [4] = "d"
}
}
}
2.การใช้ Split แบบกำหนดจำนวนผลลัพธ์ที่ต้องการ
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string myString = "101,a,b,c,d";
string[] items = myString.Split(new[] { ',' }, 2);
// [0] = "101"
// [1] = "a,b,c,d"
}
}
}
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string myString = "101,a,b,c,d";
string[] items = myString.Split(new[] { ',' }, 3);
// [0] = "101"
// [1] = "a"
// [2] = "b,c,d"
}
}
}
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string myString = "101,a,b,c,d";
string[] items = myString.Split(new[] { ',' }, 4);
// [0] = "101"
// [1] = "a"
// [2] = "b"
// [3] = "c,d"
}
}
}
3.การใช้ Split ด้วย multiple separator characters
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
string[] items = text.Split(delimiterChars);
// [0] = "one"
// [1] = "two"
// [2] = "three"
// [3] = "four"
// [4] = "five"
// [5] = "six"
// [6] = "seven"
}
}
}
4.การใช้ Split ด้วย string
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string[] separatingChars = { "<<", "..." };
string text = "one<<two......three<four";
string[] items = text.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries );
// [0] = "one"
// [1] = "two"
// [2] = "three<four"
}
}
}