/* Program to return first location in the string s1 where any charater in a string s2 occurs or -1 if s1 does not contain any character in s2 */
#include<stdio.h>
#include<limits.h>
int main(void)
{
char s1 [] = "This is fun";
char s2 [] = "fin";
int loc = theF(s1, s2);
printf("%d", loc);
printf("\n");
return 0;
}
int theF(char s1 [], char s2 [])
{
int i = 0;
int loc = -1;
while (s1[i] != '\0')
{
int j = 0;
while (s2[j] != '\0')
{
if (s2[j] == s1[i])
{
loc = (int)s1[i];
return loc;
}
j++;
}
i++;
}
return loc;
}
編寫函數字符串s1返回所述第一位置的任何(S1,S2),該字符串中返回 第一位置s1發生字符串s2中的任何 字符,如果s1發生則爲-1 不包含s2中的任何字符。例如,任何(「This is fun」,「fin」)返回 2,('f'出現在位置8,'i'出現在2中,並且 'n'在10中),而任何很有趣「,」死「)返回 -1。寫功能的任何(S1,S2),在其中在一個字符串s2任何字符發生
方向^^
你們看到任何問題嗎?它返回105當它應該返回8.我檢查ASCII表,並將不具有相關性8遺憾D:
您正在返回該位置的字符代碼,而不是位置本身。猜猜'105'代表什麼字符。 – usr2564301
您應該檢查字符匹配的i和j組合,而不是字母'loc =(int)s1 [i];'告訴您字母105匹配。 105是'我'。 – Chirality
作爲參考,這最終會非常接近標準庫函數'strpbrk'。 –