c# - 为什么我的字符串没有转换为整数?
问题描述
我有一个项目列表,每个项目都有数字,后跟一个空格,然后是一个单词。想想拼字游戏。
36 喜欢 36 喜欢 27 朋友 31个氨基 28 错
我正在尝试使用 2 位数字作为组织项目,我可以按值的顺序对单词进行排名。
我的列表 ComJoined 如上所示。
我的代码是:
for (int i = 0; i < ComJoined.Count; i++)
{
if (i + 1 <= ComJoined.Count)
{
int one = (Convert.ToInt32(ComJoined[i].Substring(0, 2)));
int two = Convert.ToInt32(ComJoined[i + 1].Substring(0, 2));
if (one <= two)
{
string Stuff = ComJoined[i];
ComJoined.Insert(i + 1, Stuff);
ComJoined.RemoveAt(i);
}
}
}
出于某种原因,它说“输入字符串的格式不正确”。我读到这意味着字符串没有 int 值,但被转换的部分,前两位数字,显然有。为什么会出现这种情况?
解决方案
对于您的问题的解决方案,这可能不太复杂:
var words = new SortedDictionary<int, string>();
foreach (var com in ComJoined)
{
string[] splitCom = com.Split(' ');
// Assuming your data is in the correct format. You could use TryParse to avoid an exception.
words.Add(int.Parse(splitCom[0]), splitCom[1]);
}
// Do something with the sorted dictionary...
foreach (KeyValuePair<int, string> word in words)
Console.WriteLine("{0} {1}", word.Key, word.Value);
推荐阅读
- c - pthread_join 参数类型错误
- jquery - 如何先返回
- python - 如何比较python中的两个字典列表(JSON)并仅输出它们之间的变化?
- php - PHP 迁移 5 到 7,关于检查内容的建议
- javascript - 在“AR.JS”中更改对象(.dae 或 gltf)的颜色
- xpath - 不同日期的 ImportXML 抓取
- android - 如何正确使用 withIndex 和 takeUntil 、forEachWhile 和 RxJava?
- android - Flutter - Webview_plugin - 我无法启用全屏视频
- r - 按位置(按列给出)在data.frame的一行中选择值并替换它
- r - 大块中的希腊字母未正确显示