2016-01-30 42 views
-1

任何人可以幫助我與我的代碼字符串中的字符搜索

int main(void){ 

    int ctr,wordLength; 

    char theWord[99]; 

    ctr = 0; 

    printf("Enter a Word: "); 
    scanf("%s", &); 
    printf("Enter the letter you want to find: "); 
    scanf("%s", &); 

    while(ctr < wordLength | theWord[ctr]=='a'){ 

ctr++; 
    } 

//output 
} 

期待輸出

輸入一個字:你好

輸入你要查找的字母:

在字中未找到字母z。

+1

你是什麼意思'的scanf( 「%S」,&);'的意思??? – haccks

+0

我留空白,我不知道我應該怎麼輸入 –

回答

0
  • 你能做到這樣也

    #include <stdio.h> 
    int main(void) 
    { 
        int ctr; 
        char theWord[99], ch; 
        ctr = 0; 
        printf("Enter a Word: "); 
        scanf("%s", theWord); 
        printf("Enter the letter you want to find: "); 
        scanf(" %c", &ch); 
    
        for(int i = 0; theWord[i]; i++) 
        { 
        if(theWord[i] == ch) 
         ctr++; 
        } 
        if(ctr != 0) 
        printf("word is found\n"); 
        else 
        printf("word is not found\n"); 
    } 
    
  • 是的,我們可以做到這一點NG while循環也

    int i = 0; 
    while(theWord[i] != '\0') 
    { 
        if(theWord[i] == ch) 
        ctr++; 
        i++; 
    } 
    if(ctr != 0) 
        printf("word is found\n"); 
    else 
        printf("word is not found\n"); 
    
+0

好建議。您可能想用'scanf(「%98s」,theWord)保護條目;'並測試返回值'scanf'。 – chqrlie

+0

你也可以保存一個變量,通過不計算字符來簡化代碼(只要顯示+返回,如果找到) –

+0

@chqrlie實際上,它似乎必須使用* while *循環(它是* for * btw)到標題 –

-1

我做你的代碼的修正,它成功地運作與GCC

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

int main(void){ 

    int ctr = 0,c = 0, wordLength; 

    char ch, theWord[99]; 

    printf("Enter a Word: "); 
    scanf("%s", theWord); 
    printf("Enter the letter you want to find: "); 
    scanf("%c", & ch); 

    wordLength = strlen(theWord); 

    while(theWord[ctr] != '\0') 
    { 
     if (theWord[ctr] == ch) 
     { 
      printf("the letter %c is found in the word\n", ch); 
      c++; 
     } 
     ctr++; 
    } 
     if (c == 0) 
     { 
     printf("the letter %c is NOT found in the word\n", ch); 
     } 
} 
+0

的scanf(「%S」,& ch); C++;? – ninja

+0

這不是字符串搜索。即使是這樣,你的代碼是不正確 – ninja

+0

@ninja對不起 –

0

更正代碼

int main (void) 
{ 
    int ctr = 0; 
    int wordLength; 
    char theWord[99], ch; 

    printf("Enter a Word: "); 
    scanf("%s", theWord); 

    printf("Enter the letter you want to find: "); 
    scanf("%c", &ch); 

    while (theWord [ctr] != '\0') 
    { 
     if (theWord [ctr] == ch) 
     { 
      print("Character found at position %1", ctr); 
      break; 
     } 
     ctr++; 
    } 
    if (theWord [ctr] == '\0') 
    { 
     printf ("Character not found"); 
    } 
} 
+2

這很可能會搜索「\ n''。使用'scanf(「%c」,&ch);'忽略掛起的'\ n'。 – chqrlie