C# IndexOf() 用法理解

The String IndexOf() method returns the index of the first occurrence of the specified character/substring within the string.

IndexOf()函数返回指定字符在字符串中第一次出现的索引位置。

复制代码
 1 using System;  
 2 namespace CsharpString {  
 3   class Test {
 4     public static void Main(string [] args) {
 5      
 6       string str = "Ice cream";
 7 
 8       // returns index of substring cream
 9       int result = str.IndexOf("cream");
10     
11       Console.WriteLine(result);   
12  
13       Console.ReadLine();    
14     }
15   } 
16 }
17 
18 // Output: 4
复制代码

-1 if the specified character/string is not found。

如果返回值是-1,表示指定字符没有找到。

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Drawing;
 6 using System.Windows.Forms;
 7 
 8 namespace InDexOfDemo
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             string str = "abcdefjhigk";
15             
16             int index_one = 1;
17             int num = str.IndexOf("c", 1);
18             Console.WriteLine("在字符串中自第{0}个字符查找字母c,c的位置是{1}",index_one+1,num);
19 
20             int index_two = 2;
21             int numb = str.IndexOf("c", 2);
22             Console.WriteLine("在字符串中自第{0}个字符查找字母c,c的位置是{1}", index_two + 1, numb);
23 
24             int index_thr = 3;
25             int numbe = str.IndexOf("c", 3);
26             Console.WriteLine("在字符串中自第{0}个字符查找字母c,c的位置是{1},即:没有查找到c", index_thr + 1, numbe);
27         }
28     }
29 }
复制代码

 

posted @   chenlight  阅读(2838)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示