Example of Linux C string replacement function

  • 2020-05-17 07:33:29
  • OfStack

Example of Linux C string substitution function

Recently, I learned the basic programming knowledge of linux, string replacement function, and found some information on the Internet. I think this article is well written. Write it down and share it with you.

Example code:


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

 

/**
*
* @author: cnscn@163.com
* @reference: lovesnow1314@http://community.csdn.net/Expert/TopicView3.asp?id=5198221 
*
*  With the new substring newstr Replace the source string src In the first len Is contained within the character oldstr substring 
*
* @param char* dest  The target string, which is the new string replaced 
* @param const char* src  Source string, the replaced string 
* @param const char* oldstr  The old substring, the substring that will be replaced 
* @param const char* newstr  New substring 
* @param int len  Before being replaced len A character 
*
* @return char* dest  Returns the address of the new string 
*
*/
char *strreplace(char *dest, char *src, const char *oldstr, const char *newstr, size_t len)
{
// If the strings are equal, return directly 
if(strcmp(oldstr, newstr)==0)
return src;

// Pointer to substring position 
char *needle;

// Temporary memory area 
char *tmp;

// Assigns the source string address to the pointer dest That let dest and src All point to src Memory region 
dest = src;

// If I find a substring ,  And the substring is in the front len Substring range ,  I'm going to substitute ,  Otherwise just go back 
while((needle = strstr(dest, oldstr)) && (needle -dest <= len))
{
// Allocate new space : +1  Is to add the end of the string '\0' terminator 
tmp=(char*)malloc(strlen(dest)+(strlen(newstr)-strlen(oldstr))+1);

// the src In the former needle-dest Memory space data, copy to arr
strncpy(tmp, dest, needle-dest);

// End of identity string 
tmp[needle-dest]='\0';

// The connection arr and newstr,  Namely the newstr Attached to the arr The tail ,  To form a new string ( Or an array of characters )arr
strcat(tmp, newstr);

// the src In the   from oldstr The partial sum after the substring position arr Connected to the 1 Rise and form a new string arr
strcat(tmp, needle+strlen(oldstr));

// Put to use malloc Allocated memory, copied to the pointer retv
dest = strdup(tmp);

// The release of malloc Allocated memory space 
free(tmp);
}

return dest;
}

int main()
{
char *str="wo i love iyou";
char *old="i";
char *new="ILOVEYOUYA";

char *dest;
// Allocated memory space :  The size of the  == src The length of the   +  newstr and oldstr The length of the differential ( It could be plus or minus 0)+1
printf("%s\n",strreplace(dest, str, old, new,1));
printf("%s\n",strreplace(dest, str, old, new,5));
printf("%s\n",strreplace(dest, str, old, new,40));

return 0;
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: