首页 > 解决方案 > 为什么我的字符串没有转换为整数?

问题描述

我有一个项目列表,每个项目都有数字,后跟一个空格,然后是一个单词。想想拼字游戏。

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 值,但被转换的部分,前两位数字,显然有。为什么会出现这种情况?

标签: c#

解决方案


对于您的问题的解决方案,这可能不太复杂:

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);

推荐阅读