2016-10-04 128 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爲真,因此條件爲真。