字符串查找---查找子字符串在原字符串第一次出现时的起始索引

一,问题描述:

给定两个不同长度的字符串,查找短字符串在长字符串中第一次出现时的索引。

比如:s = "I come from china, You come from India" ,  t = "from"

此时"from"在 s 中第一次出现的索引为 7

二,算法分析:

依次扫描字符串 s 中的每个字符,开始一轮判断:若 s 中字符和 t 中字符相同,则获取 s 的下一个字符和 t 的下一个字符...

直至到t的末尾或者在某个点处 s 中字符与 t 中字符不相等了。

前者表明 t 字符串在 s 字符串中;后者表明,从s的当前字符开始,t 不在 s 中,

那么此时 s 就扫描下一个字符,再开始下一轮判断

三,代码如下:

 1 public class StringIndex {
 2     
 3     public static void main(String[] args) {
 4         String s = "I come from china, You come from India";
 5         String t = "from";
 6         int r_begin = strIndex(s.toCharArray(), t.toCharArray());
 7         System.out.println(r_begin);
 8  9 
10     //查找t 在 s中第一次出现时,t在 s中的起始索引
11     public static int strIndex(char[] s, char[] t){
12         int k_begin = -1;//标记 t 在 s中的起始位置
13         for(int index = 0; index < s.length; index++)// 对 s 中的每个字符由 while开启一轮比较
14         {
15             int i = index;//字符串s 从 index 处开始和 字符串 t 比较
16             int j = 0;
17             while((i < s.length && j < t.length) && (s[i++] == t[j++]))
18                 ;
19             if(j == t.length)//字符串 t 出现在了 字符串 s 中
20             {
21                 k_begin = index;//记录下字符串 t 出现在 s中的起始位置,程序返回该位置
22                 break;
23             }
24         }
25         return k_begin;
26     }
27

另外可参考JDK类库:String类的indexOf(String )方法

原文地址:https://www.cnblogs.com/hapjin/p/5382961.html