華為的一道比較基礎的面試題,就是查找一個字符串中某個子字符串出現的次數,並只考慮最左對齊的情況。
如在"helloejesjhelloejedjshhello"中查找子字符串"hello"出現的次數。
最直接的方法是使用遍歷實現。
int string_find( char str[], char substr[] )
{
int i, j, check ,count = 0;
int len = strlen( str ); /*取得字符串長度,不包括'\0'*/
int sublen = strlen( substr );
for( i = 0; i < len; i++ )
{
check = 1; /*檢測標記*/
for( j = 0; j + i < len && j < sublen; j++ ) /*逐個字符進行檢測,在sublen長度內,一旦出現不同字符便將check置為0*/
{
if( str[i + j] != substr[j] )
{
check = 0;
break;
}
}
if( check == 1 ) /*在sublen長度內的字符都相等*/
{
count++;
i = i + sublen; /*調整檢測起始位置*/
}
}
return count;
}