简体   繁体   English

如何用等效的strcat()代替memcpy()?

[英]How can I replace memcpy() with an equivalent strcat()?

I have the following code that works properly inserting a substring into a specific part of the original string. 我有以下代码可以正常工作,将子字符串插入原始字符串的特定部分。 How can I do the same thing using strcat() instead of memcpy() ? 如何使用strcat()而不是memcpy()做同样的事情?

void insertString(char original[], int start, int length, char toInsert[]){
  size_t insertlen = strlen(toInsert);
  size_t origlen = strlen(original);
  char *m = malloc(origlen - length + insertlen);
  memcpy(m, &original[0], start);
  memcpy(m+start, &toInsert[0], insertlen);
  memcpy(m+start+insertlen, &original[start+length], origlen-length+insertlen);
  strcpy(original,m);
}

Where char original[] is the original string, int start is the element which the substring should start at, int length is the length of the substring being removed from original[] and char toInsert[] is the substring being inserted. 其中char original[]是原始字符串, int start是子字符串应从其开始的元素, int length是要从original[]删除的子字符串的长度,而char toInsert[]是要插入的子字符串。

Example to clarify : 举例说明:

ex. 例如 if original[] = default string 1 , start = 5 , length = 6 , toInsert[] = hello world 如果original[] = default string 1start = 5length = 6 ,则toInsert[] = hello world

the resuling m would equal 'defauhello worlding 1' since the substring being replaced in this example is 'lt str' starting at 5 chracters in and is 6 characters long. 由于在此示例中要替换的子字符串是从5个字符开始的'lt str',并且长度为6个字符,因此,结果m等于'defauhello worlding 1'。 How can I do the same thing with strcat() instead of memcpy() ? 如何用strcat()而不是memcpy()做同样的事情?

You can use strncat and do it in the below way. 您可以使用strncat并按照以下方式进行操作。 But, please note that the below doesn't handle error conditions and other constraints which you have as a part of this problem. 但是,请注意,下面的内容不能解决错误条件和作为此问题一部分的其他约束。

void insertString(char original[], int start, int length, char toInsert[]){
  size_t insertlen = strlen(toInsert);
  size_t origlen = strlen(original);
  size_t newBuffLen = origlen - length + insertlen + 1
  char *m = malloc(newBuffLen);
  memset(m, 0, newBuffLen);
  strncat(m, original, start);
  strncat(m, toInsert, insertlen);
  strncat(m, original + start+ length, origlen-start-length);
  strcpy(original,m);
}

I have replaced it with the following and it works perfectly 我已将其替换为以下内容,并且效果很好

void insertString(char original[], int start, int length, char toInsert[]){
  size_t insertlen = strlen(toInsert);
  size_t origlen = strlen(original);
  char holder[origlen - length + insertlen];
  strcpy(holder,"");
  strncat(holder,original,start);
  strcat(holder,toInsert);
  strncat(holder, &original[start+length], origlen-length+insertlen);
  strcpy(original,holder);
}

Thank you all for your help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM