语法:IndexOf(String value, int startIndex);
功能:报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。
参数:value 要搜寻的字符串。
startIndex 搜索起始位置。
返回值:如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 的索引位置;否则为 -1。 如果 value 为 System.String.Empty,则返回值为startIndex。
语法:IndexOf(char value, int startIndex);
功能:报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。
参数:value 要查找的 Unicode 字符。
startIndex 搜索起始位置。
返回值:如果找到该字符,则为从字符串的起始位置开始的 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 textBox4_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text.IndexOf(textBox3.Text, Convert.ToInt32(textBox4.Text)).ToString();
}
}
}
当要查询的字符是“s”,查询的起始位置是0到7之间的时候,查询结果字符位置为7,即第一个“s”;
当要查询的字符是“s”,查询的起始位置是8到12之间的时候,查询结果字符位置为12,即为第二个“s”;
当要查询的字符是“s”,查询的起始位置大于13的时候,无法查询到字符“s”,返回值为 -1;
语法:IndexOf(String value, int startIndex, int count);
功能:报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。
参数:value 要搜寻的字符串。
startIndex 搜索起始位置。
count 要检查的字符位置数。
返回值:如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 的索引位置;否则为 -1。 如果 value 为 System.String.Empty,则返回值为startIndex。
语法:IndexOf(char value, int startIndex, int count);
功能:报告指定字符在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。
参数:value 要查找的 Unicode 字符。
startIndex 搜索起始位置。
count 要检查的字符位置数。
返回值:如果找到该字符,则为从字符串的起始位置开始的 value 从零开始的索引位置;否则为 -1。
private void textBox5_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text.IndexOf(textBox3.Text, Convert.ToInt32(textBox4.Text), Convert.ToInt32(textBox5.Text)).ToString();
}
当要查询的字符是“s”,查询的起始位置从0开始的时候,查询的字符位置数量为0到7之间的时候,无法查询到字符“s”,返回值为 -1;此时将查询的起始位置改为1,即可查询到“s”。
当要查询的字符是“s”,查询的起始位置从0开始的时候,查询的字符位置数量为0到7之间的时候,无法查询到字符“s”,返回值为 -1;