C++ c字符串复制无法清空字符串
我假设通过一个字符串删除字母g,不使用任何内置函数,只有一个变量,必须是指针,不允许使用括号。我有代码,但它一直返回空字符串,而不是新编辑的字符串C++ c字符串复制无法清空字符串,c++,string,pointers,C++,String,Pointers,我假设通过一个字符串删除字母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 siz
#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.
}
#包括
使用名称空间std;
void deleteG(字符*str){
char*temp=str;//创建新指针,指向现有指针,现在我已初始化并具有足够的大小。
while(*str!='\0'){//,而c字符串未达到空终止
如果(*str!=“g”|*str!=“g”){//如果当前位置的值不是字符g或g,则继续。
*temp=*str;//将值复制到
temp++;//增加计数
}
str++;//将计数增加到下一个字符,并再次检查上面的is是否不等于g或g
}
//现在应该将新字符串复制到旧字符串,覆盖所有字符
而(*temp!='\0'){
*str=*温度;
str++;
temp++;
}
}
int main(){
char msg[100]=“我记得拉各斯格斯旁边的玻璃门,靠近金桥。”;
deleteG(msg);
不能将其更改为:
if (*str != 'g' && *str != 'G') {
此条件检查字母是否不是g,无论大小写如何
if (*str != 'g' || *str != 'G') {
此条件始终为真,因此它始终复制角色
你会问,为什么总是这样
想想看,这个角色要么是g,要么是g,或者其他什么
如果是g,则*str!=“g”
为假,*str!=“g”
为真,为假| |为真
为真,因此条件为真
如果是G,则*str!=“G”
为真,*str!=“G”
为假,为真|为假
为真,因此条件为真
如果它是其他的,那么*str!=“g”
是真的,*str!=“g”
是真的,是真的
是真的,所以条件是真的。一切都不是g
或者不是g
。是的,复制字符串时不带g或者GYou必须使用&&而不是|
,否则任何没有意义的东西都会通过。Everything不是g
或notg
。唯一一个“notg
或notg
”的东西如果是假的,那么这两个字母都是g
和g
,而这两个字母都不是。想象一下从A到Z和A到Z的每个字母。你把所有不是g
或不是g
的字母都放在一堆里——每个字母都会在那堆里。哪个字母不会不在那堆里?@DavidSchwartz啊哈哈哈哈哈哈哈哈哈哈哈,我明白了,对。这是有意义的谢谢你,这对我很有帮助。只是想知道如何添加空终止字符,可能需要做不同类型的循环。thanks@BaummitAugen我做了吗?顺便说一下,我删除了我的评论,不管帖子是用任何内置函数写的>代码> @ KEYY-NYEP,因为正如我所说的,C++是可怕的SOM。etimes.(作为参考,Ken建议比较std::toupper(*str)!=“G”
,而不必与&
进行比较。我声称这可能是UB。)还必须编辑代码,在到达旧字符串末尾时向前移动空字符,并使新字符变短,这样就不会打印其他字符。