替换字符串中的单词

时间:2014-04-17 12:28:05

标签: c string

我试图用另一个词替换句子中的单词。 对于前者如果str1 =“strong”且str2 =“weak”,则str中的第一个字符串应该更改为“如果核心很弱,则不会出错”。 我正在收到分段错误(核心转储)错误。

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

void func(char *str,char *str1,char *str2,int l1,int l2)
{
 int i,m,j,c;

 for(i=0;*(str+i)!='\0';i++)
    {
      if(*(str+i)==*str1)
       {
        for(m=i,j=0;j<l1;m++,j++)       /*checking the equality of the two words*/
         {
          if(*(str+m)!=*(str1+j))
            break;
          else
           c=1;
         }
        if(c==1)
        { 
          for(j=i;*(str+j)!='\0';j++)
             *(str+j+l2-l1)=*(str+j);
          for(m=0,j=i;(*(str2+m)!='\0');j++,m++)
            *(str+j)=*(str2+m);
        }
       }
    }
}

int main()
{
  char *str[]={
              "If the core is strong, you can't go wrong",
              "Canada's wonder of the world",
              "Processing a sorted array",
              "Was that a joke?", 
              "I wanna be a millionaire",
              "Your post is not properly formatted"
             };

 int i,l1,l2,k,j;
 char str1[10],str2[10];
 l1=strlen(str1);
 l2=strlen(str2);
 printf("Enter string 1 : ");
 scanf("%s",str1);
 printf("\nEnter string 2 : ");
 scanf("%s",str2);

 for(k=0;k<=5;k++)
  func(str[k],str1,str2,l1,l2);    

 for(i=0;i<6;i++)
  {
    printf("\n");
    for(j=0;*(str[i]+j)!='0';j++)
      printf("%c",*(str[i]+j));
  }

 return 0;
} 

2 个答案:

答案 0 :(得分:0)

 char *str[]={
              "If the core is strong, you can't go wrong",
              "Canada's wonder of the world",
              "Processing a sorted array",
              "Was that a joke?", 
              "I wanna be a millionaire",
              "Your post is not properly formatted"
             };

这将创建一个字符指针数组,每个指针指向一个字符串文字,如果修改字符串文字,它将导致分段错误,因为它位于只读内存中。这就是你得到分段错误的原因 在代码中也要检查逻辑错误。

答案 1 :(得分:0)

不幸的是,您的代码在许多级别上都是错误的。其他人已经在strlen() scanf()之前指出了字符串文字问题以及main()之前的问题,但有更多错误:

1.您尝试就地编辑字符串。如果用较长的字符串替换子字符串会发生什么?你试图向前移动字符串。但是 意味着你写过分配给字符串的内存的末尾。这是未定义的行为,可能会崩溃。

2.在func()

[snip]
if(c==1)
    { 
      for(j=i;*(str+j)!='\0';j++)
         *(str+j+l2-l1)=*(str+j);
      for(m=0,j=i;(*(str2+m)!='\0');j++,m++)
        *(str+j)=*(str2+m);
    }

您迭代直到源字符串以空终止,但您不复制空终止符!稍后,您尝试printf()字符串(逐个字符,由于一些不可思议的原因,也没有检查空终止符,但是对于ASCII '0' ...),然后由于缺少空终止而崩溃。

要解决您的问题,您可以执行以下操作:

1.使用strstr()遍历字符串以查找要替换的子字符串。计算子串的出现次数 2.使用strlen()中的func()来确定子字符串的长度和替换。将差异乘以子字符串的出现次数,以查找新字符串的长度或长度。将差值添加到原始字符串的strlen()以找出要分配的内存量(请记住为空终止分配额外的字节)。
3.使用malloc()分配所需的内存 4.使用strcpy()/strncpy()/memmove()/strstr()/whatever standard library functions you need的组合来组合新字符串。

相关问题