C语言综合练习1:字符串原地操作

1 删除字符串中的逗号

方法1:逗号后面的字符逐个往前挪

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <string.h>

void ch_back(char* str) {
	*str = '\0';				//若当前str是字符串的最后一个非空字符
	while (*(str + 1) != '\0')	//若当前str不是字符串的最后一个非空字符
	{
		*str = *(str + 1);
		str++;
	}
	*str = '\0';			//删掉了字符,最后一个字符已往前推,因此原来最后一个的位置要置空
}
char* remove_ch(char* str1) {
	int i = 0;
	char* str2;
	while (*str1 == ',' && *str1 != '\0') str1++;	//跳过开头的逗号

	str2 = str1;
	while (*str2 != '\0')
	{
		while(*str2 == ',') ch_back(str2);
		str2++;
	}
	return str1;
}
int main04() {
	char buf1[] = "ajgdlgj,,,, hhgj ljljgo, hllj";
	char buf2[] = ",,,ajgdlgj,,, h,";
	char* str;

	str = remove_ch(buf1);
	printf("%s\n", str);

	str = remove_ch(buf2);
	printf("%s\n", str);
	return 0;
}

方法2:逐个复制非逗号的字符

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <string.h>

char* remove_ch(char* str1, int len) {
	int i = 0, j = 0, k = 0;

	for (i = 0; i < len; i++)		//统计非逗号元素的个数
	{
		if (str1[i] != ',') k++;
	}

	for (i = 0; i < k; i++)			//替换
	{
		while (str1[j] == ',' && j < len) j++;
		str1[i] = str1[j];
		j++;
	}
	str1[k] = 0;						//最后一个置\0
	return str1;
}
int main() {
	char buf1[] = "ajgdlgj,,,, hhgj ljljgo, hllj";
	char buf2[] = ",,,ajgdlgj,,, h,";
	char* str;

	str = remove_ch(buf1, sizeof(buf1) / sizeof(buf1[0]));
	printf("%s\n", str);

	str = remove_ch(buf2, sizeof(buf2) / sizeof(buf2[0]));
	printf("%s\n", str);
	return 0;
}

2 删除字符数组中的\0

需求:
将字符串中的\0放到普通字符的后面,如“a\0b\0c\0”->“abc\0\0\0”
本题折磨了我两小时,中间尝试了字符串的拼接、字符串整体向前移动、寻找下一个非空索引等方法,这些方法非常繁琐。最快的是先统计字符串中非零元素的个数,再按顺序逐个寻找非空字符,然后复制到相应的位置,尽量避免对索引进行操作。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
char* remove0(char* str, int len)
{
	int i = 0, j = 0, k = 0;

	for (i = 0; i < len; i++)		//统计非零元素的个数
	{
		if (str[i] != '\0') k++;
	}

	for (i = 0; i < k; i++)			//替换
	{
		while (str[j] == '\0' && j < len) j++;
		str[i] = str[j];
		j++;
	}
	str[k] = 0;						//最后一个置\0
}

int main() {
	char buf1[] = "\0a\0b\0\0\0c";
	char buf2[] = "\0\0\0aj\0gd";
	remove0(buf1, sizeof(buf1) / sizeof(buf1[0]));
	printf("%s\n", buf1);
	remove0(buf2, sizeof(buf2) / sizeof(buf2[0]));
	printf("%s\n", buf2);
	return 0;
}

总结

从上面两道题的编写可知,字符串原地操作时,先寻找符合条件的字符总数,然后逐个复制到相应位置最为方便

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值