C语言字符串的动态操作
C语言中的字符串,相比C++,少了许多动态操作函数,比如没有动态删除字符串开头或末尾元素的函数,也没有动态追加字符串的函数,为了一劳永逸,仿写了C++中的push_back(), push_front(), pop_back(), pop_front(), append()等函数。这些函数都是修改了自己本身,同时也可能改变了内存地址。
实现代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* 对于下列函数的第一个参数,只能传入像char * s = "hello"这样声明的指针s
* 不能使用 char s2[] = "hello" 中的数组名s2,
* 毕竟这样声明的字符串数组不能改变
*/
// 末尾添加元素
char* push_back(char * st, char ch)
{
int len = strlen(st) + 2;
char tmp[len];
strcpy(tmp, st);
tmp[len - 2] = ch;
tmp[len - 1] = '\0';
free(st);
st = (char*)malloc(len * sizeof(char));
strcpy(st, tmp);
return st;
}
// 头部添加元素
char* push_front(char * st, char ch)
{
int len = strlen(st) + 2;
char tmp[len];
tmp[0] = ch;
strcat(tmp, st);
free(st);
st = (char*)malloc(len * sizeof(char));
strcpy(st, tmp);
return st;
}
// 删除首个元素
char* pop_front(char * st)
{
int len = strlen(st);
char tmp[len];
for (int i = 0; i < len - 1; ++i)
tmp[i] = st[i + 1];
tmp[len - 1] = '\0';
free(st);
st = (char*)malloc(len * sizeof(char));
strcpy(st, tmp);
return st;
}
// 删除末尾元素
char* pop_back(char * st)
{
int len = strlen(st);
char tmp[len];
for (int i = 0; i < len - 1; ++i)
tmp[i] = st[i];
tmp[len - 1] = '\0';
free(st);
st = (char*)malloc(len * sizeof(char));
strcpy(st, tmp);
return st;
}
// 末尾添加字符串
char* append(char * st, const char * s)
{
int len = strlen(st) + strlen(s) + 1;
char tmp[len];
strcpy(tmp, st);
strcat(tmp, s);
free(st);
st = (char*)malloc(len * sizeof(char));
strcpy(st, tmp);
return st;
}
int main()
{
char *s = "hell";
s = push_back(s, 'o');
printf("%-15s%p\n", s, (void*)s);
s = push_back(s, ',');
printf("%-15s%p\n", s, (void*)s);
s = push_back(s, 'M');
printf("%-15s%p\n", s, (void*)s);
s = push_front(s, '1');
printf("%-15s%p\n", s, (void*)s);
s = pop_front(s);
printf("%-15s%p\n", s, (void*)s);
s = push_back(s, 'a');
printf("%-15s%p\n", s, (void*)s);
s = pop_back(s);
printf("%-15s%p\n", s, (void*)s);
s = append(s, "AT!");
printf("%-15s%p\n", s, (void*)s);
free(s); // 记得释放内存
return 0;
}
代码在CLion上运行通过