2016-03-09 82 views
-1

任务要求首先确定字符串str1是否是str2的子字符串。如果是这样,str1中str1的起始位置将被返回。C - 递归字符串中子字符串的位置

int instring (char *str1, char *str2); 
void main() { 
    char *str1 = (char*) malloc (strlen(str1)*sizeof(char)); 
    char *str2 = (char*) malloc (strlen(str2)*sizeof(char)); 
    char ch; 
    int i = 0; 
    while (ch != '\n'){ 
     ch = getchar(); 
     str1[i] = ch; 
     i++; 
    } 
    str1[i] = '\0'; 
    i = 0; 
    char ch1; 
    while (ch1 != '\n'){ 
    ch1 = getchar(); 
    str2[i] = ch1; 
    i++; 
    } 
    str2[i] = '\0'; 
    printf("%d", instring(str1, str2)); 
    return 0; 
} 
int instring(char *str1, char *str2){ 
    int r; 
    if(*str1==0) return(0); 
    if(*str2==0) return -1; 
    if(*str1==*str2 && instring(str1+1,str2+1)==0) return(0); 
    r=instring(str1,str2+1); 
    if(r!=-1) return(r+1); 
    } 

案例1: 实施适用于: STR1 = “Mediolan” STR2 = “MMediolan”

它返回1,这是正确的。

案例2: 但是它并不适用于: STR1 = “Mediolan” STR2 = “Mediolana”

返回-1。

我被困在这里,不知道如何重写代码,所以案例2将被正确照顾。

+0

分配到'char'的getchar的'的返回值()'是自找麻烦。 – EOF

回答

2

对于启动,这是错误的

char *str1 = (char*) malloc (strlen(str1)*sizeof(char)); 
char *str2 = (char*) malloc (strlen(str2)*sizeof(char)); 

哗哗str1你指的是strlen

而且,你永远不低于

char ch1; 
while (ch1 != '\n'){ 

初始化ch1你不应该阅读的变量,你没有初始化的值。 ch也一样。


也许你想尝试这个版本(好像在我身边工作):

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

#define MAXLEN 200 

int instring (char *str1, char *str2); 

int main (void) 
{ 

    char *str1, *str2; 
    int ch = 0; 
    int i = 0; 

    str1 = malloc (MAXLEN); 
    if(str1 == NULL) return 1; 
    str2 = malloc (MAXLEN); 
    if(str2 == NULL) {free(str1); return 1;} 

    while((ch = getchar()) != EOF && ch != '\n') 
    { 
     str1[i] = (char) ch; 
     i++; 
    } 
    str1[i] = '\0'; 

    i = 0; 
    while((ch = getchar()) != EOF && ch != '\n') 
    { 
     str2[i] = (char) ch; 
     i++; 
    } 
    str2[i] = '\0'; 

    printf("%d", instring(str1, str2)); 
    free(str1); free(str2); 
    return 0; 
} 

int instring(char *str1, char *str2) 
{ 
    int r = 0; 
    if(*str1 == 0) return 0; 
    if(*str2 == 0) return -1; 
    if(*str1 == *str2 && instring(str1 + 1, str2 + 1) == 0) return 0; 
    r = instring(str1, str2 + 1); 
    if(r != -1) return (r + 1); 
} 
+0

它不幸。 STR1 =“Mediolan”,STR2 =“MMediolana” 返回0 –

+0

不是真的,在上面的例子中,它应该返回1. –

+0

@GoldsmithEdelman AAH只注意到你想去的地方字符串包含 –