[英]How to split numbers from string in C#
我有一個字符串格式的國家列表,如下所示:
123 USA, America
126 South Africa, Africa
我想拆分國家/地區代碼、國家/地區名稱和大陸並將其保存在列表或數組中。 國家/地區代碼將按該順序具有索引 [0]、國家/地區名稱 [1] 和大陸 [2]。
我試過這個:
string number = "123 USA, America";
string[] numbers = number.Split(',');
但這只會將字符串分成兩部分:“123 USA”和“America”,我也希望能夠將數字部分分開
嘗試拆分以下交替:
(?<=[0-9]) |,
這表示要在前面有數字的空格或逗號后跟空格上進行拆分。
示例代碼:
string number = "123 USA, America";
string[] parts = Regex.Split(number, @"(?<=\d) |, ");
foreach (string part in parts)
{
Console.WriteLine(part);}
}
這打印:
123
USA
America
嘗試重載Split
接受char
/ string
數組:
var splitted = number.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
結果是: string[3] { "123", "USA", "America" }
您可以使用IndexOf
查找特定字符的索引,然后使用Substring
將其分開。 IE
string number = "123 USA, America";
int index = number.IndexOf(' ');
string countryCode = number.Substring(0, index);
請注意,這僅在您的字符串格式真正一致時才有效。 如果任何字符串沒有國家/地區代碼,就會發生錯誤。
你可以這樣試試
https://dotnetfiddle.net/uY021W
public static void Main()
{
string number = "123 USA, America";
string[] delimiters = {
@" ",
@","
};
var chunks = number.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for( int i=0;i< chunks.Count();i++)
{
Console.WriteLine(chunks[i]);
}
}
嘗試這個:
public class Country
{
public int Number { get; set; }
public string Name { get; set; }
public string Continent { get; set; }
public static List<Country> Parse(string[] objects)
{
List<Country> countries = new List<Country>();
foreach (string obj in objects)
{
try
{
string[] tokens = obj.Split(',');
string[] first_portion_tokens = tokens[0].Split(' ');
countries.Add(new Country()
{
Number = int.Parse(first_portion_tokens[0]),
Name = string.Join(" ", first_portion_tokens.Skip(1).ToArray()),
Continent = tokens[1].Trim()
});
}
catch (System.Exception)
{
// invalid token
}
}
return countries;
}
}
並像這樣使用它:
string[] myObjects = new string[] { "123 USA, America" , "126 South Africa, Africa" };
List<Country> countries = Country.Parse(myObjects);
嘗試使用正則表達式
using System.Text.RegularExpressions
Regex rx = new Regex(@"?<=[0-9]",RegexOptions.Compiled | RegexOptions.IgnoreCase);
text = "your text here"
MatchCollection matches = rx.Matches(text); //matches is the numbers in your text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.