2016-02-12 30 views
3

编写代码,以检查是否s2是只使用一个呼叫isSubStrings1转动(即waterbottleerbottlewat旋转)。旋转的字符串

我写这个程序,但我无法得到所需的输出。请指导我哪里出错。

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

int isRotated(char *s1, char *s2); 
int isSubstring(char *s1, char *s2); 

int isRotated(char *s1, char *s2) 
{ 
     int r; 
     char s[100]; 
     if(strlen(s1) == strlen(s2)) 
       strcpy(s, s1); 
     r = isSubstring(s, s2); 
     strcat(s, s1); 
     return r; 
} 

int isSubstring(char *s1, char *s2){ 
     if(strstr(s1, s2)) 
       return 1; 
     else  
       return 0; 
} 

int main(void) { 
     char s1[100], s2[100]; 
     printf("Enter the first String\n"); 
     scanf("%s", s1); 
     printf("Enter the second String\n"); 
     scanf("%s", s2); 

     if(isRotated(s1, s2)==1) 
       printf("%s and %s are rotated string\n", s1, s2); 
     else 
       printf("%s and %s are not rotated string\n", s1, s2); 

     return 0; 
} 
+0

什么是STrings' ????? –

+0

“你期望的输出”究竟是什么意思?你得到了什么?错误消息? –

+0

如果两个字符串有不同的长度,'s'是未初始化的,这意味着'isSubString'和'strcat'可能在未正确终止的字符串上运行。 –

回答

3

如果你做strstr()您正在搜索的字符串旋转一个子比较。所以你在做什么是找到例如字符串s1 ABCD在另一个字符串s2 CDAB。所以实际上s2中没有子串s1,你的功能int isSubString(char *s1,char *s2)将总是返回false

一个简单的解决方案就是不直接比较s1和s2。您必须将s2与s1的双倍副本进行比较:您可以看到该字符串包含子字符串ABCD,并且您的函数将返回true。

这将意味着你的函数:

int isRotated(char *s1,char *s2) 
{ 
    char s[200]; 
    strcpy(s,s1); // Copy content of s1 to s 
    strcat(s,s1); // Append s again with the content of s1 

    if(strstr(s,s2)) 
     return 1; 
    else 
     return 0; 
} 
+2

这样比较好,但是对于不同长度的字符串可能会失败。另外,你已经实现了'isRotated',而不是'isSubString'。 –

5

要检查是否s2s1旋转,你可能要集中2个s1 S,并尝试在新的字符串找到s2

有必要检查s1s2的长度。例如,s1是“ABCD”,s2是“CDA”。那么s是“AB CDA BCD”。 strstr(s, s2) == 1,但很明显,s2不是轮转的s1

另外,我想先拨打strcmp(),因为我认为“ABCD”是“ABCD”本身的旋转。但是,这只是一个定义问题。

int isRotated(char *s1, char *s2) 
{ 
     char s[199]; 
     if(strlen(s1) != strlen(s2)) 
       return 0; 
     else if(strcmp(s1, s2) == 0) 
       return 1; 
     else 
       strcpy(s, s1); 
     strcat(s, s1); 
     return isSubString(s, s2); 
} 

BTW: “子” 就是一个字,所以它可能是更好的改变isSubString()isSubstring()

+0

打我吧! :) – Wossname

+0

请注意,'strstr()'不会返回'int',它会将'char *'返回到找到的子字符串,因此您的文本有点混乱。 – unwind

+1

我现在修好了,'如果'strstr(s,s2)!= NULL',isSubString()'会返回'1' –

0

这个怎么样,使用串连-和查找的子串的方法:

int isRotated(const char *s1, const char *s2) 
{ 
    const size_t l1 = strlen(s1); 
    const size_t l2 = strlen(s2); 
    if(l1 != l2) 
    return 0; 
    char joined[2 * l1 + 1]; 
    memcpy(joined, s1, l1); 
    memcpy(joined + l1, s1, l1); 
    joined[2 * l1] = '\0'; 
    return strstr(joined, s2) != NULL; 
} 

基本上使用更多的const,可变长度的数组来处理不同的长度,当我们知道我们正在复制的长度时,使用memcpy()