C# C从字符串中获取值
我有一根这样的绳子C# C从字符串中获取值,c#,string,foreach,int,C#,String,Foreach,Int,我有一根这样的绳子 string myString = [0,4,5,5,6]; 我想通过foreach循环获得该字符串的每个值,例如,如何继续?假设您忘记在字符串周围加引号: 您需要循环遍历每个字符,并尝试将其解析为一个数字 //A list to hold the result List<int> values = new List<int>(); //loop through each character 1 by 1 foreach(var c in mySt
string myString = [0,4,5,5,6];
我想通过foreach循环获得该字符串的每个值,例如,如何继续?假设您忘记在字符串周围加引号: 您需要循环遍历每个字符,并尝试将其解析为一个数字
//A list to hold the result
List<int> values = new List<int>();
//loop through each character 1 by 1
foreach(var c in myString)
{
//will hold the value
int num = 0;
//Try to parse the character into an integer
var isNumber = int.TryParse(c.ToString(), out num);
//if the parsing succeeded add it to the list
if(isNumber)
{
values.Add(num);
}
}
这将把值0,4,5,5,6输出到值列表中,忽略所有非数字,为什么不这样使用linq呢
List<int> = myString.Select(Int32.Parse).ToList();
这看起来更像一个带数字的数组…?这不是一个字符串,这是一个整数数组如果这是javascript当然了你确定这是一个字符串吗?它可能是指定字符代码的字符数组吗?或者你忘记加引号了吗?是的,这是一个来自api的字符串,而不是你问题中代码块中的JSONI:1。这就是JSON数组语法。2.这不是一个字符串。它也是无效的。