c++ - 修剪空格 C++ POINTERS

标签 c++ string pointers append

我在函数 trim 中编写了一个简单的函数来修剪文本中的空格。 它几乎可以工作。我有一个问题,因为它也应该改变原始字符串,但它没有。问题是什么?请描述。我感谢任何帮助。谢谢:) 代码:

#include <iostream>
#include <string.h>
using namespace std;

char* trim(char *str) {

    while(*str==' '){
        *str++;
    }

    char *newstr = str;

    return newstr; 
}


int main(){
    char str[] = "   Witaj cpp", *newstr;

    cout << "start" << str << "end" << endl;    // start   Witaj cppend

    newstr = trim(str);

    cout << "start" << str << "end" << endl;    // startWitaj cppend

    cout << "start" << newstr << "end" << endl;    // startWitaj cppend

    return 0;
}

最佳答案

不应该更改原始字符串 - 即使像 *str=something; 这样的代码也不会出现。 修改原来的字符串,可以这样写

char* trim(char *str) {
    char* oldstr = str;

    while(*str==' '){
        str++;//*str++; // What's the point of that *
    }


    char *str2 = oldstr;

    while(*str!='\0'){
        *(str2++) = *(str++);
    }
    *str2 = '\0';

    return oldstr;


}

关于c++ - 修剪空格 C++ POINTERS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699751/

相关文章:

c++ - Pugixml - 将 xml 元素内容转换为 C++ 数组

c++ - C++中的引用是如何用指针实现的

java - 部分比较 2 个字符串

java - replace ('\0' ,'0' ) 是什么意思?

java - 在字符串中第一次出现整数时拆分字符串

c - C 中矩阵的迭代器和指针

c - 什么时候 uintptr_t 优于 intptr_t?

c++ - 从 C C++ 中的文件中读取矩阵

c++ - std::map<struct, int> 我需要析构函数吗?

c++解析带格式的字符串