菜学C++ Day40

前缀形式,在表达式计算之前完成自增或自减

自增运算符++优先级高于解引用操作符*

这里是继续昨天的例题

有非常多方法

#include<iostream>
using namespace std;
void f0(char*);
void f1(char*);
void f2(char*);
void f3(char*);
void f4(char*);
void f5(char*);
int main() {
	char str[] = "Today     is Wednesday,      and the weather     is sunny.";
    //f换成f0或者f1、f2……
	f(str);
	cout << str;
	return 0;
}
/*
没有考虑到下一位字符也是空格应该怎么办
所以只删除了一个空格字符
*/
void f0(char* p) {
	while (*p) {
		if (*p == ' ')
			*p = *(p + 1);
		p++;
	}
}
/*
因为原长度大于删掉空格字符的长度
f1是没有删除掉原长度后面的经多次赋值的值
*/
void f1(char* p) {
	while (*p) {
		//i是空格 n是结束符之前
		int i = 1, n = 0;
		if (*p == ' ') {
			while (*(p + i) == ' ')
				i++;
			while (*(p + n + i)) {
				*(p + n) = *(p + n + i);
				n++;
			}
		}
		p = p + 1;
	}
}
//在f1基础上将冗余的字符赋值为\0
void f2(char* p) {
	int sum = 0, length = strlen(p);
	char* q = p;
	while (*q) {
		int i = 1, n = 0;
		if (*q == ' ') {
			while (*(q + i) == ' ')
				i++;
			sum += i;
			while (*(q + n + i)) {
				*(q + n) = *(q + n + i);
				n++;
			}
		}
		q = q + 1;
	}
	//从删除了空格的字符串最后开始,到真正q长度结束为止
	q = p + length - sum;
	while (*q) {
		*q = '\0';
		q++;
	}
}
void f3(char* p) {
	char* q = p, * r = p;
	while (*r) {
		if (*r != ' ') {
			/*
			后缀形式,在表达式计算之后完成自增
			自增运算符++优先级高于解引用操作符*
			先赋值运算符 再分别后移、
			计算赋值 计算后移 解引用
			*/
			*q++ = *r++;
		}
		//将不为空的r赋值给q
		else r++;
	}
	*q = '\0';
}
//缺点:默认第一个字符不为空
void f4(char* p) {
	char* q = p, * r = p;
	while (*++r)
		if (*r != ' ')
			*++q = *r;
	*(q + 1) = '\0';
}
void f5(char* p) {
	char* temp1 = p;
	while (*temp1) {
		int i = 0;
		while (*(temp1 + i + 1) == ' ') {
			i += 1;
		}
		if (i > 0) {
			//temp1 temp2都是地址传递
			char* temp2 = temp1 + 1;
			//将后续的字符都向前移动
			while (*temp2) {
				*temp2 = *(temp2 + i);
				temp2 += 1;
			}
			*temp2 = '\0';
		}
		temp1 += 1;
	}
}

直接换了一个主函数的append方法
 

#include<iostream>
using namespace std;
//append追加字符串或字符
int main()
{
	string test = "Today     is Wednesday, and the weather     is sunny.";
	string result = "";
	for (int i = 0; test[i] != '\0'; i++)
	{
		if (test[i] != ' ')
			result.append(1, test[i]);
		else
			if (test[i + 1] != ' '){
				result.append(1, test[i + 1]);
				i++;
			}
	}
	cout << result;
}

这是请教了很多朋友综合起来的结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值