【问题标题】:How to search for a specified number in a string as a whole如何在整个字符串中搜索指定的数字
【发布时间】:2020-07-17 22:18:03
【问题描述】:

我的英语不是很好,请原谅我。我想在字符串中搜索一个数字并获取下一个字符。让我们以数字 6 为例。当我搜索它时,它找到了数字 6,但它是数字 16 的一部分。我想找到整个数字 6,而不是另一个数字的一​​部分。

for (int i = 0; i < 6; i++)
            {
                int i2 = i + 1;
                answer = readTxt;
                answer = answer.Replace(" ", String.Empty);
              //  MessageBox.Show(answer);
                answer = answer.Substring(answer.IndexOf(i2 + ".") + 2, 1); //Search for number and get the text next to it

                //add answers to listbox
                listBox1.Items.Add(answer);
                string answrLetter = listBox1.Items[i].ToString();
               }

我想在“答案”变量中搜索那个数字。变量的内容很大,所以我不会放在这里

【问题讨论】:

  • “旁边的文字”是什么意思?下一个角色?也许提供一个例子会很棒。文中有更多的6吗?如果是,您需要全部还是只需要第一个?
  • @szkup 抱歉,我没有很好地解释它。我想获得下一个 1 个字符。是的,文本中有更多的 6,因为有像 16、56、36 这样的数字

标签: c# string substring indexof


【解决方案1】:

您可以使用 for 循环遍历 string,并使用 Char.IsNumber (see documentation) 检查前一个字符是否不是数字。要检查字符的数值是否等于 i2,请使用 @987654326 @(see documentation.)

for (int j = 0; j < answer.Length - 1; j++)
{
    if ((j == 0 || !Char.IsNumber(answer, j - 1)) && Char.GetNumericValue(answer, j) == i2 && answer[j + 1] == '.')
        //you find i2 at position j, the previous character (if exists) is not a number, the next character is '.'
}

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多