如何整体搜索字符串中的指定数字

问题描述 投票:-1回答:1

我的英语不是很好,请原谅我。我想在字符串中搜索一个数字并获取下一个1个字符,以数字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();
               }

我想在“答案”变量中搜索该数字。变量的内容很大,因此我不会在此处放置它

c# string substring indexof
1个回答
0
投票

您可以通过for循环遍历string,并用Char.IsNumbersee documentation检查前一个字符是否不是数字。)要检查字符的数值是否等于i2,请使用Char.GetNumericValuesee 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 '.'
}
© www.soinside.com 2019 - 2024. All rights reserved.