2012-07-27 32 views
0

找到C中第一個單詞迴文的開始?
示例:Hello mom and dad, how is it going?
mom是第一個。找到作爲迴文的第一個單詞的開頭

什麼是最有效的方法?

的char * find_first_palindrome(字符*輸入)

+2

歡迎堆棧溢出。您需要向我們展示您已經嘗試過的內容,並且您可能希望將作業標籤添加到您的帖子中。 – 2012-07-27 00:52:54

+0

告訴我們你試過了什麼,那麼只有我們會幫助你。 – 2012-07-27 01:37:36

+0

如果這是家庭作業,請標記爲這樣。 – 2012-07-27 03:16:38

回答

0

GET一字一句,看到只有第一和最後一個字符,如果它等於再繼續進一步的驗證,否則去下一個單詞。

main() 
{ 
    string a = "Hello mom and dad, how is it going?"; 
    printf("first_palindrome word = %s",first_palindrome(a)); 
} 

char * first_palindrome(string abc) 
{ 

    for(i=0;i<number_of_words;i++) 
    { 
    write logic will send word by word... 
    if(palindrome(word)) 
    { 
     return word; 
    } 
    } 
return "no_word_found"; 
} 
+0

...並在此之前,正確地格式化代碼。 – 2012-07-27 06:43:27

1

這是我的解決方案。它能解決問題,但可能不是最有效的方法。希望它可以幫助你。

int find(char* c)//for single word 
{ 
    int n=strlen(c); 
    for(int i=0;i<n/2;i++) 
    { 
     if (c[i]!=c[n-i-1]) 
      return false; 
    } 
    return true; 
} 

char* findlong (char* lc)//for long sentence 
{ 
    int i; 
    char* end=lc+strlen(lc); 
    for(;;) 
    { 
     for(i=0;lc[i];i++) 
     { 
      if(lc[i]==' ') 
      { 
       lc[i]='\0'; 
       break; 
      } 
     } 
     if(find(lc) && !ispunct(*lc))//modified here,add !ispunct(*lc) to make it more robust. 
      return lc; 

     lc += i+1; 
     if (lc>end)  //modified here. add this sentence. 
     { 
      printf("no word found!\n"); 
      return NULL; 
     } 
    } 
} 

int main() 
{ 
    //test cases 
    char b[]="fasdg"; 
    char c[]="Hello, mom and dad, how is it going?"; 
    char d[]="Hello , mom and dad, how is it going?";//the single comma won't be returned 
                //as a palindrom  

    char* result=findlong(c); 
    if (result) 
     printf("%s\n",result); 

    return 0; 
} 
+0

+1,但cout是C++不是C - 請正確讀取標籤。 – 2012-07-27 06:44:28

+0

yes.i知道它,但cout <<比printf()更容易輸入。此外,C++部分只出現在驗證部分,而不是解決它的實際代碼。 – duleshi 2012-07-27 06:51:28

+0

我必須承認,我有點懶惰地使用printf().... – duleshi 2012-07-27 06:52:22

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

int isPalindrome(const char *str){ 
    const char *front, *back; 
    front=str; 
    back =str + strlen(str)-1; 
    for(;front<back;++front,--back){ 
     while(!isalpha(*front))++front;//isalnum? 
     while(!isalpha(*back))--back; 
     if(front > back || tolower(*front)!=tolower(*back)) 
      return 0; 
    } 
    return 1; 
} 

int main(){ 
    const char *data="Hello mom and dad, how is it going?"; 
    char *p, *src; 
    p=src=strdup(data); 
    for(;NULL!=(p=strtok(p, " \t\n,.!?"));p=NULL){ 
     if(isPalindrome(p)){ 
      printf("%s\n", p); 
      break; 
     } 
    } 
    free(src); 
    return 0; 
} 
相關問題