前缀形式,在表达式计算之前完成自增或自减
自增运算符++优先级高于解引用操作符*
这里是继续昨天的例题
有非常多方法
#includeusing 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++;
}
}
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基础上将冗余的字符赋值为
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 = ' ';
q++;
}
}
void f3(char* p) {
char* q = p, * r = p;
while (*r) {
if (*r != ' ') {
*q++ = *r++;
}
//将不为空的r赋值给q
else r++;
}
*q = ' ';
}
//缺点:默认第一个字符不为空
void f4(char* p) {
char* q = p, * r = p;
while (*++r)
if (*r != ' ')
*++q = *r;
*(q + 1) = ' ';
}
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 = ' ';
}
temp1 += 1;
}
}
直接换了一个主函数的append方法
#includeusing namespace std; //append追加字符串或字符 int main() { string test = "Today is Wednesday, and the weather is sunny."; string result = ""; for (int i = 0; test[i] != ' '; i++) { if (test[i] != ' ') result.append(1, test[i]); else if (test[i + 1] != ' '){ result.append(1, test[i + 1]); i++; } } cout << result; }
这是请教了很多朋友综合起来的结果



