'How to split a string by a specific character? [duplicate]
Possible Duplicate:
How do i split a String into multiple values?
I have a string 0001-102525 . I want to split it into 0001 and 102525.How can i do it? Regards,
Solution 1:[1]
var myString = "0001-102525";
var splitString = myString.Split("-");
Then access either like so:
splitString[0] and splitString[1]
Don't forget to check the count/length if you are splitting user inputted strings as they may not have entered the '-' which would cause an OutOfRangeException.
Solution 2:[2]
How about:
string[] bits = text.Split('-');
// TODO: Validate that there are exactly two parts
string first = bits[0];
string second = bits[1];
Solution 3:[3]
You can use C# split method - MSDN
Solution 4:[4]
string strData = "0001-102525";
//Using List
List<string> strList = strData.Split('-').ToList();
string first = strList.First();
string last = strList.Last();
//Using Array
string[] strArray = strData.Split('-');
string firstItem = strArray[0];
string lastItem = strArray[1];
Solution 5:[5]
string myString = "0001-102525";
//to split the string
string [] split = myString.Split("-");
//to display the new strings obtained to console
foreach(string s in split)
{
if(s.Trim() !="")
Console.WriteLine(s);
}
Solution 6:[6]
string strToSplit = "0001-102525"; //Can be of any length and with many '-'s
string[] arrStr = strToSplit.Split('-');
foreach (string s in arrStr) //strToSplit can be with many '-'s. This foreach loop to go thru entire arrStr string array
{
MessageBox.Show(s);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jon Skeet |
| Solution 3 | eakgul |
| Solution 4 | Elias Hossain |
| Solution 5 | Samuel Liew |
| Solution 6 | Raktim Biswas |
