【问题标题】:How can I find multiple occurrences of a substring in another and do 'some' operations?如何在另一个子字符串中找到多次出现并执行“某些”操作?
【发布时间】:2016-10-28 17:41:17
【问题描述】:

这里我试图在一个字符串中找到一个子字符串,将子字符串反转并替换为原始字符串。如果我用 if 条件替换 while 循环,它适用于第一次出现。但我希望它适用于多次出现。 如果我在while循环中运行它(while(str = strstr(str,substr)),它会导致分段错误。我正在使用代码块IDE。 那么,如何更改代码以使其适用于多次出现?

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

int main()
{
char *str = malloc(100);
char *sbstr = malloc(20);
int i=0,flag=1;;
printf("%s\n","Enter string");
gets(str);
printf("%s\n","Enter substring");
gets(sbstr);
/////////////////////////////////////////////////////////////

while(str = strstr(str,sbstr))
    {

        memcpy(str,strrev(sbstr),strlen(sbstr));

    }

////////////////////////////////////////////////////
    printf("%s",str);
    return 0;

}

【问题讨论】:

  • 当您使用strncpy() 时,它会在复制的字符串末尾添加一个空终止符。由于您要复制到源字符串中,因此您已将字符串截断到该点。
  • 在我尝试深入研究您的代码之前,您是否已经通过 GDB 等调试器对其进行了调试? Valgrind 也是检查内存泄漏的有用工具。另外,一定要用-Wall -Wextra编译。
  • 使用memcpy() 而不是strncpy(),所以它不会添加空终止符。
  • 另外,当你循环时,你应该在旧匹配之后开始新的搜索。否则,如果您正在搜索回文,则可能会出现无限循环,因为在您反转它后它将保持不变。
  • 我可以看到您已通过编辑帖子中从 strncpy()memcpy() 的行来回复评论者的建议。 (在其他地方也是如此)不建议这样做,因为它会导致那些试图回答问题的人移动目标。只需通过其他评论确认您理解该评论,或者如果在答案中,如果有帮助,请向上单击答案。

标签: c string


【解决方案1】:

更好、更有效的循环是:(仔细看)

char* first_p; //will store the address of the first character of sbstr in str if it does  


while(i < LENGTH_OF_STR) //if smaller than the length of the main array
{

    if(str[i] == sbstr[k])
    {  
        k++: 
        if(k == LENGTH_OF_SBSTR)
        {
           //sbstr is in str 
           first_p = str+i-LENGTH_OF_SBSTR-1; //now first_p stores the pointer to the first letter
           reverse(first_p,LENGTH_OF_SBSTR);// reversing the string 
           break;
        }
    }
    else
    {
        k = 0; 
    }

    i++;

}

void reverse(char *toReverse,int len)
{   
    int i;
    char temp;

    for (i=len-1; i >= len/2; i--)
    {
        temp = toReverse[i];
        toReverse[i] = toReverse[len-1-i];
        toReverse[len-1-i] = temp;
    }

 }

【讨论】:

  • 如果您认为这篇文章有帮助,请为这篇文章投票:)。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2015-10-08
  • 2022-11-17
  • 2018-12-19
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多