我有一个字符串0001-102525。我想把它分成0001和102525.How我能做到吗? 的问候,
答案 0 :(得分:12)
string myString = "0001-102525";
string[] splitString = myString.Split("-");
然后像这样访问:
splitString[0]
和splitString[1]
如果您要分割用户输入的字符串,请不要忘记检查计数/长度,因为它们可能没有输入“ - ”,这会导致OutOfRangeException
。
答案 1 :(得分:9)
怎么样:
string[] bits = text.Split('-');
// TODO: Validate that there are exactly two parts
string first = bits[0];
string second = bits[1];
答案 2 :(得分:5)
您可以使用C#split方法 - MSDN
答案 3 :(得分:0)
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];
答案 4 :(得分:0)
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);
}
答案 5 :(得分:0)
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);
}