语法:IndexOf(String value);
功能:报告指定字符串在此实例中的第一个匹配项的从零开始的索引。
参数:value 要搜寻的字符串。
返回值:如果找到该字符串,则为 value 的从零开始的索引位置;如果未找到该字符串,则为 -1。 如果 value 为 System.String.Empty,则返回值为0。
语法:IndexOf(char value);
功能:报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。
参数:要查找的 Unicode 字符。
返回值:如果找到该字符,则为 value 的从零开始的索引位置;如果未找到,则为 -1。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace indexof
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "我喜欢学习visual studio C#";
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text.IndexOf(textBox3.Text).ToString();
}
}
}
当查找字符“我”时,字符位置为0,说明字符串中的字符位置是从0开始的。
当查找字符“s”时,字符位置为7,说明字符串中的字符位置显示的是第一个“s”的位置。
当查找字符“t”时,字符位置为13,说明字符串中空格也占位置。
当查找字符串“su”时,字符位置为7,说明字符串中字符串的位置为字符串中第一个字符的位置。
当查找字符串“sul”时,字符位置为-1,说明字符串没有该字符串,因为只能查找连续的字符串,“sul”应该是“sual”。