2016-03-07 28 views
0
/* 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:

+1

您正在返回該位置的字符代碼,而不是位置本身。猜猜'105'代表什麼字符。 – usr2564301

+1

您應該檢查字符匹配的i和j組合,而不是字母'loc =(int)s1 [i];'告訴您字母105匹配。 105是'我'。 – Chirality

+3

作爲參考,這最終會非常接近標準庫函數'strpbrk'。 –

回答

2

loc = (int)s1[i];不返回字符的位置,但字符值本身在ASCII。你想要返回的是i,loc = i;

0

正如我的評論和其他許多人所說的,你要返回字符的值而不是位置(i/j)的值。下面的固定代碼與一些小的編碼差異。雖然循環可能會讓我感到困惑,所以使用for循環來說明它會循環直到兩個字符串的全長看起來更容易閱讀。

#include <stdio.h> 
#include <string.h> 

int any(char s1 [], char s2 []); 

int main(void){ 
    char s1 [] = "This is fun"; 
    char s2 [] = "fin"; 

    int loc = any(s1, s2); 

    if (loc == -1){ printf("No matching chars\n"); } 
    else { printf("%d\n", loc); } 

    return 0; 
} 

int any(char s1 [], char s2 []){ 

    int i = 0, j = 0; 

    for (i = 0; i < strlen(s1); i++){ 
     for (j = 0; j < strlen(s2); j++){ 
      if (s1[i] == s2[j]){ 
       return i; // i+1 depending on literal placement 
         // vs zero indexed arrays 
      } 
     } 
     j=0; 
    } 

    return -1; 

} 

正如Steve Summit提到的,這也正是該功能strpbrk()一樣。使用它的簡單實現將是:

#include <stdio.h> 
#include <string.h> 

int main(){ 
    const char s1[] = "This is fun"; 
    const char s2[] = "fin"; 
    char *ret; 

    ret = strpbrk(s1, s2); 
    if(ret){ 
     printf("First matching character: %c\n", *ret); 
    } else { printf("No matching chars\n"); } 

    return(0); 
} 
相關問題