这是我的3个整数的字符串,我想将它存储在3个整数变量中,但我无法找到答案。
string orders = "Total orders are 2222 open orders are 1233 closed are 222";
这就是我想要做的。
int total = 2222;
int close = 222;
int open = 1233;
答案 0 :(得分:5)
尝试使用正则表达式(提取模式)和 Linq (将它们组织到int[]
):
string orders = "Total orders are 2222 open orders are 1233 closed are 222";
int[] result = Regex
.Matches(orders, "[0-9]+")
.OfType<Match>()
.Select(match => int.Parse(match.Value))
.ToArray();
答案 1 :(得分:4)
你只能使用Linq:
int[] result = orders
.Split(' ')
.Where(s => s
.ToCharArray()
.All(c => Char.IsDigit(c)))
.Select(s => Int32.Parse(s))
.ToArray();
答案 2 :(得分:1)
这是一种方式
namespace StringToIntConsoleApp
{
class Program
{
static void Main(string[] args)
{
string orders = "Total orders are 2222 open orders are 1233 closed are 222";
string[] arr = orders.Split(' ');
List<int> integerList = new List<int>();
foreach(string aString in arr.AsEnumerable())
{
int correctedValue ;
if(int.TryParse(aString,out correctedValue))
{
integerList.Add(correctedValue);
}
}
foreach (int aValue in integerList)
{
Console.WriteLine(aValue);
}
Console.Read();
}
}
}
答案 3 :(得分:0)
您可以依次检查每个字符并查看它是否为数值:
string orders = "Total orders are 2222 open orders are 1233 closed are 222";
List<int> nums = new List<int>();
StringBuilder sb = new StringBuilder();
foreach (Char c in orders)
{
if (Char.IsDigit(c))
{
//append to the stringbuilder if we find a numeric char
sb.Append(c);
}
else
{
if (sb.Length > 0)
{
nums.Add(Convert.ToInt32(sb.ToString()));
sb = new StringBuilder();
}
}
}
if (sb.Length > 0)
{
nums.Add(Convert.ToInt32(sb.ToString()));
}
//nums now contains a list of the integers in the string
foreach (int num in nums)
{
Debug.WriteLine(num);
}
输出:
2222
1233
222
答案 4 :(得分:0)
我会这样做:
var intArr =
orders.Split(new[] { ' ' }, StringSplitOptions.None)
.Select(q =>
{
int res;
if (!Int32.TryParse(q, out res))
return (int?)null;
return res;
}).Where(q => q.HasValue).ToArray();
答案 5 :(得分:0)
这将从字符串中提取整数:
var numbers =
Regex.Split(orders, @"\D+")
.Where(x => x != string.Empty)
.Select(int.Parse).ToArray();
输出
numbers[0] == 2222
numbers[1] == 1233
numbers[2] == 222
答案 6 :(得分:-1)
int[] results = orders.Split(' ').Where(s => s.ToCharArray().All(c => Char.IsDigit(c)))
.Select(s => Int32.Parse(s)).ToArray();