一、字符串替换
用法1:直接在字符数组里面完成。
str_replace(要替换的内容, 替换后的内容, 原始字符串所在的字符数组, 字符数组的大小);
例如
char str[100];
strcpy(str, "this is good");
str_replace("is", "*", str, sizeof(str));
用法2:另外分配空间存放新字符串。
新字符串 = str_replace(要替换的内容, 替换后的内容, 原始字符串, -1);
例如
char *s = str_replace("is", "*", "this is good", -1);
if (s != NULL)
{
printf("%s\n", s);
free(s);
}
二、删除两端空格
trim(字符数组);
例如
char str[] = " this ";
int len = trim(str);
printf("%s\n", s);
#include <stdlib.h>
#include <string.h>
char *str_replace(const char *search, const char *replace, char *subject, int bufsize)
{
char *p;
int i, j = 0, n = 0;
int len, slen, rlen, tlen;
// check arguments
if (subject == NULL)
{
return NULL;
}
tlen = strlen(subject);
if (bufsize == -1)
{
// make sure subject is writable
p = malloc(tlen + 1);
if (p == NULL)
{
return NULL;
}
memcpy(p, subject, tlen + 1);
subject = p;
}
if (search == NULL || search[0] == '\0')
{
return subject;
}
slen = strlen(search);
if (replace == NULL)
{
replace = "";
}
rlen = strlen(replace);
// find out how many replacements are needed
for (i = 0; subject[i] != '\0'; i++)
{
if (subject[i] != search[j])
{
// character mismatch
j = 0;
}
if (subject[i] == search[j])
{
j++;
if (j == slen)
{
// pattern match
subject[i + 1 - j] = '\0'; // front
subject[i] = '\0'; // rear
j = 0;
n++;
}
}
}
if (n == 0)
{
return subject;
}
// calculate the length of the new string and check buffer size
len = tlen + n * (rlen - slen);
if (bufsize == -1)
{
if (len > tlen)
{
// increase buffer size
p = realloc(subject, len + 1);
if (p == NULL)
{
free(subject);
return NULL;
}
subject = p;
}
}
else if (bufsize < len + 1)
{
return NULL;
}
// replace substrings
if (len <= tlen)
{
i = 0; // for read
j = 0; // for write
while (i < tlen)
{
if (subject[i] == '\0')
{
memcpy(subject + j, replace, rlen);
i += slen;
j += rlen;
}
else
{
subject[j] = subject[i];
i++;
j++;
}
}
}
else
{
i = tlen - 1;
j = len - 1;
while (i >= 0)
{
if (subject[i] == '\0')
{
memcpy(subject + j + 1 - rlen, replace, rlen);
i -= slen;
j -= rlen;
}
else
{
subject[j] = subject[i];
i--;
j--;
}
}
}
subject[len] = '\0';
return subject;
}
int trim(char *s)
{
int i, j = -1, len = 0;
for (i = 0; s[i] != '\0'; i++)
{
if (j == -1 && s[i] != ' ' && s[i] != '\t')
{
j = 0;
}
if (j != -1)
{
s[j] = s[i];
j++;
if (s[i] != ' ' && s[i] != '\t')
{
len = j;
}
}
}
s[len] = '\0';
return len;
}