2012-07-27 65 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; 
} 
相关问题