做網(wǎng)站找誰好廣州網(wǎng)站推廣
找出字符串第一個匹配的下標
給你兩個字符串 haystack
和 needle
,請你在 haystack
字符串中找出 needle
字符串的第一個匹配項的下標(下標從 0 開始)。如果 needle
不是 haystack
的一部分,則返回 -1
。
public int strStr(String haystack, String needle) {int len1 = haystack.length();int len2 = needle.length();if (len1 < len2){return -1;}for (int i = 0; i <= (len1 - len2); i++) {if(haystack.substring(i,i+len2).equals(needle)){return i;}}return -1;}