获取字符串中重复字符的索引

本文关键字:字符 索引 字符串 获取 | 更新日期: 2023-09-27 18:26:59

我有一个文本框,其中包含文本"aaaaa"。如果我用鼠标选择任何"a",它将返回所选文本的索引。然而,我总是得到零的指数。

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = Convert.ToString(textBox1.Text.IndexOf(textBox1.SelectedText));
}

有人能帮我得到真正的索引吗

获取字符串中重复字符的索引

我相信您想要的是TextBox.SelectionStart属性。这将在选择开始的文本框中为您提供索引。

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = textBox1.SelectionStart.ToString();
}