【问题标题】:c string copy fails to empty stringc字符串复制失败为空字符串
【发布时间】: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”为假的东西是gG,什么都不是。想象一下从 A 到 Z 和 a 到 z 的每个字母。你把所有不是G 或不是g 的字母都放在一堆——每个字母都在那个堆里。哪一封信不会在那堆里?
  • @DavidSchwartz 啊啊啊我明白了,正确。有道理谢谢你,这对我来说帮助很大。只是想弄清楚如何添加空终止字符,可能需要执行不同类型的循环。谢谢

标签: c++ string pointers


【解决方案1】:
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为真,所以条件为真。

【讨论】:

    【解决方案2】:

    改成:

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

    此条件检查字母是否不是 g,不考虑大小写。

    【讨论】:

    • @BaummitAugen 我做到了吗?顺便说一句,我删除了我的评论,不管帖子上写的是with out using any built in functions
    • @KenY-N 是的,因为stackoverflow.com/questions/21805674/… 正如我所说,C++ 有时很糟糕。 (作为参考,Ken 建议比较 std::toupper(*str) != 'G' 而不是必须与 &amp;&amp; 比较。我声称这可能是 UB。)
    • 还必须编辑代码以在到达旧字符串末尾时将空字符向前移动,并使新的字符更短,因此不会打印其他内容。
    猜你喜欢
    • 2011-04-07
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多