如何按特定字符拆分字符串
本文关键字:拆分 字符串 字符 何按特 | 更新日期: 2023-09-27 18:16:42
可能重复:
如何将字符串拆分为多个值?
我有一根绳子0001-102525。我想把它分成0001和102525。我该怎么做?问候,
var myString = "0001-102525";
var splitString = myString.Split("-");
然后像这样访问:
splitString[0]
和splitString[1]
如果要拆分用户输入的字符串,请不要忘记检查计数/长度,因为它们可能没有输入"-",这会导致OutOfRangeException
。
怎么样:
string[] bits = text.Split('-');
// TODO: Validate that there are exactly two parts
string first = bits[0];
string second = bits[1];
您可以使用C#拆分方法-MSDN
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];
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);
}
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);
}