【发布时间】:2016-10-04 00:34:55
【问题描述】:
我想通过一个字符串并删除字母 g,不使用任何内置函数,只有一个变量,它必须是一个指针并且不允许使用括号。我有代码,但它一直返回一个空字符串,而不是新编辑的字符串。
#include <iostream>
using namespace std;
void deleteG(char *str) {
char *temp = str; //make new pointer,pointing at existing, now i have initialized and enough size.
while (*str != '\0') { //while the c-string does not reach null termination
if (*str != 'g' || *str != 'G') { // if the value of the current position is not the character g or G proceed.
*temp = *str;//copy value over
temp++;//increase count
}
str++;//increase count to next char and check again above is if does not equal g or G
}
//this should now copy the new string over to the old string overriding all characters
while (*temp != '\0') {
*str = *temp;
str++;
temp++;
}
}
int main() {
char msg[100] = "I recall the glass gate next to Gus in Lagos, near the gold bridge.";
deleteG(msg);
cout << msg; // prints I recall the lass ate next to us in Laos, near the old bride.
}
【问题讨论】:
-
一切要么不是
g,要么不是G。 -
是的,复制字符串不带 g 或 G
-
你必须使用 && 而不是 ||,否则一切都会过去
-
这毫无意义。 Everything 不是
g或不是G。唯一“不是g或不是G”为假的东西是g和G,什么都不是。想象一下从 A 到 Z 和 a 到 z 的每个字母。你把所有不是G或不是g的字母都放在一堆——每个字母都在那个堆里。哪一封信不会在那堆里? -
@DavidSchwartz 啊啊啊我明白了,正确。有道理谢谢你,这对我来说帮助很大。只是想弄清楚如何添加空终止字符,可能需要执行不同类型的循环。谢谢