[英]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.