我的英语不是很好,请原谅我。我想在字符串中搜索一个数字并获取下一个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();
}
我想在“答案”变量中搜索该数字。变量的内容很大,因此我不会在此处放置它
您可以通过for循环遍历string
,并用Char.IsNumber
(see documentation检查前一个字符是否不是数字。)要检查字符的数值是否等于i2
,请使用Char.GetNumericValue
(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 '.'
}