2016-10-04 67 views
-2

我想通过一个字符串并删除字母g,使用任何内置的函数,只有一个变量,必须是一个指针,并且不允许使用方括号。我有代码,但它一直返回一个空字符串,而不是新的编辑字符串。c字符串复制无法清空字符串

#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. 
} 
+6

一切都不是'g'或不''G'。 –

+0

是的,复制出g或G的字符串 –

+2

你必须用&&代替||,否则任何事都会通过 – ZenJ

回答

0

它更改为:

if (*str != 'g' && *str != 'G') { 

该条件检查该信克,不论箱子。

+0

@BaummitAugen我做了?顺便说一句,我删除了我的评论,无论这篇文章说“不使用任何内置函数”。 –

+1

@ KenY-N是的,因为https://stackoverflow.com/questions/21805674/do-i-need-to-cast-to-unsigned-char-before-calling-toupper正如我所说的,有时C++是可怕的。 (作为参考,Ken建议比较'std :: toupper(* str)!='G''而不是与'&&'进行比较。我声称这可能是UB。) –

+0

也必须编辑代码以移动null字符在达到旧字符串的末尾时向前移动,并使其更短,因此没有其他字符可以打印。 –

3
if (*str != 'g' || *str != 'G') { 

这种情况总是如此,所以它总是复制人物。

为什么总是这样,你问?

想一想 - 字符是g或G或其他。

如果是g,那么*str != 'g'为假,并且*str != 'G'为真,且false || true为真,因此条件为真。

如果是G,则*str != 'g'为真,并且*str != 'G'为假,且true || false为真,因此条件为真。

如果是别的,那么*str != 'g'为真,并且*str != 'G'为真,且true || true为真,因此条件为真。