【问题标题】:How to temporarily uppercase the string variable in a foreach loop? [closed]如何在 foreach 循环中临时大写字符串变量? [关闭]
【发布时间】:2020-04-19 01:50:03
【问题描述】:

我目前有以下代码:

foreach (string s in lstSearchStrings.Items)
{
    int cnt = CountSubStrings(fileText, s);
    if (cnt > 0)
    {
        string cs = cnt.ToString().PadLeft(5);
        lstCounts.Items.Add(cs);
        counter++;
    }
    else break;
}

我需要暂时大写 s 以便在已经大写的 fileText 字符串中查找它,但我不能,因为当我尝试这个时它会出错:

foreach (string s in lstSearchStrings.Items)
{
    if (chkExactCase.Checked == false)
    {
        string us = s.ToUpper();
        s = us;
    }
    int cnt = CountSubStrings(fileText, s);
    if (cnt > 0)
    {
        string cs = cnt.ToString().PadLeft(5);
        lstCounts.Items.Add(cs);
        counter++;
    }
    else break;
}

任何帮助将不胜感激!

【问题讨论】:

  • I can't because it gives an error when I try this: 总是错误是什么

标签: c# string foreach uppercase


【解决方案1】:

你不能改变循环变量s,用变量us代替:

foreach (string s in lstSearchStrings.Items)
{
    var us = chkExactCase.Checked ? s : s.ToUpper();
    int cnt = CountSubStrings(fileText, us);
    if (cnt > 0)
    {
        string cs = cnt.ToString().PadLeft(5);
        lstCounts.Items.Add(cs);
        counter++;
    }
    else break;
}

【讨论】:

  • 是的,我应该补充一点,我需要做一个 if/else 来测试它是否需要大写。但是您验证了我的解决方案,非常感谢。
【解决方案2】:

我想我明白了:

foreach (string s in lstSearchStrings.Items)
{
    int cnt = 0;
    if (chkExactCase.Checked == false)
    {
        cnt = CountSubStrings(fileText, s.ToUpper());
    }
    else
    {
        cnt = CountSubStrings(fileText, s);
    }
    if (cnt > 0)
    {
        string cs = cnt.ToString().PadLeft(5);
        lstCounts.Items.Add(cs);
        counter++;
    }
    else break;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多