【问题标题】:Replacing a substring with another string in C用C中的另一个字符串替换子字符串
【发布时间】:2011-08-28 13:32:24
【问题描述】:

我正在编写一个代码来用它的值替换所有 MACROS。 如果我的宏 MAX 的值为 1000, 并且在代码中,它必须被替换为 1000。(我假设如果 MACROS 是一行中的第一个单词,那么在该行中我们不会替换 MACROS,这种情况下我们会以不同的方式处理。

 //Code to replace MACROS BY THEIR VALUES 

 //line contains the actual one line of the code.  
 //line is initialized to contain as maximum number of charectos(say 100).

 //SrcStr is the macro  and destStr is its value. 

 //This block will be looped  for all lines.

   char* p; 
   p = strstr(line,srcStr);
   if(p != NULL)  //if the srcString is found
   {
      if(strlen(p) != strlen(line)) //special case   
      {
         if( isalnum(*(p-1)) == 0 && isalnum( *(p+strlen(srcStr)))==0 ) 
        // if the next char and prev char to our macro is not a alphabets or digits
             {
/*As answered by medo42 (below)*/     
     memmove(p+strlen(destStr), p+strlen(srcStr),strlen(p+strlen(srcStr)+1);
     memcpy(p,destStr,strlen(destStr));         
             }
           }
         else
         {/* handle differently*/}

       } 

由于我是第一次使用memmovememcopy,所以我怀疑上面的代码是否稳定并且可以正常工作。

上面的代码正确吗? 上面的代码对所有输入情况都稳定吗?

【问题讨论】:

  • 好的,这确实是一种可怕且有限的方法。了解语法树。

标签: c pointers logic memmove


【解决方案1】:

我看到至少三个问题:

  1. memmove 不应该使用sizeof(p),它总是会被修复(比如4),它应该使用strlen(line) - (p + strlen(p) - line)
  2. 您需要处理替换宏导致行长超过 100 的情况
  3. 您需要处理宏标签被符号包围的情况。即,_MACRO_ 与 MACRO 不同。

【讨论】:

  • sizeof(p) 是指针的大小,即 32 位系统上为 4,64 位系统上为 8。它与您实际要复制的数量完全无关。
  • 你真的想移动所有剩余的字节。
【解决方案2】:

if(strlen(p) != strlen(line)) 为什么不在这里简单地使用if(p != line)?这应该是等效的,更容易理解和更快(strlen 扫描整个字符串)。

isalnum(...) == 0 可能是个人喜好,但我会将该表达式写为!isalnum(...),因为这样更容易理解含义。

memmove(p+(strlen(destStr)-strlen(srcStr)),p,sizeof(p)); 这对我来说是错误的。它将根据您的指针大小移动许多字符,这没有任何意义,如果 srcStr 比 destStr 长,则移动的目标可能是行缓冲区开始之前的位置。如果您想移动行的其余部分以调整更改的长度,请尝试以下操作:memmove(p+strlen(destStr), p+strlen(srcStr), strlen(p+strlen(srcStr)+1); +1 对于移动空终止符也很重要。当然,你需要确保行缓冲区实际上提供了足够的空间。

【讨论】:

  • 感谢您的 cmets 它真的很有用。还有一个,我已经知道了,答案会很有用,这就是我在这里问这个问题的原因:-)
猜你喜欢
  • 2011-06-06
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-06-03
  • 2012-12-18
  • 2014-12-23
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多