今天來解析一下string方法中的indexof這個方法
比如:string str="你好中國";
system.out.println(str.indexof("中國"));
返回來的結果為2;
問題來了,這個string類indexof這個方法是怎麼實現的呢?
public int indexof(string str)
public int indexof(string str, int fromindex)
static int indexof(char source, int sourceoffset, int sourcecount,char target, int targetoffset, int targetcount,int fromindex)
if (fromindex < 0)
if (targetcount == 0)
//獲取使用者第乙個字元
char first = target[targetoffset];
int max = sourceoffset + (sourcecount - targetcount);
for (int i = sourceoffset + fromindex; i <= max; i++)
/* found first character, now look at the rest of v2 */
if (i <= max) }}
return -1;
}原理:
先找第乙個字元,如果找到了再找後面的字元。
也就是 j 和 k 只要匹配就都+1,往後匹配下一對。
最難的就是 end,迴圈多少次了。j和k的起始索引不同,end既能控制迴圈的次數(剛好是剩下未完成的字元次數),又能讓源陣列的索引獲取到正確的值
C語言中沒有string
c語言中有string型別變數嗎 這裡的 string 有 二 義性。1 如果 string 是普通詞彙,c語言中有字元型別變數嗎 答,有。字元型別 用 char 宣告。char str this is a string 2 如果 string 是專用詞彙,c語言中有string型別變數嗎 答,沒有...
C語言中String庫 2
2008 02 23 14 07 size t strcspn const char s1,const char s2 返回值是字串 s1的完全由不包含在字串 s2中的字元組成的初始串長度。size t strspn const char s1,const char s2 返回值是字串 s1的完全由...
c語言中的String庫
在c語言中,對字串的處理非常重要,特別在一些網路裝置中,處理過程會影響裝置的 和吞吐量。這裡詳細注釋了 string.h中的所有函式。以下內容摘自 c程式設計教程 美 h.m.deitel p.j.deitel著,薛萬鵬等譯,機械工業出版社。void memccpy void dest,const ...