修剪空间C ++ POINTERS

时间:2015-11-13 18:43:26

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

不应该更改原始字符串 - 即使像*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;


}

答案 1 :(得分:1)

您现在的代码只搜索空格。

您需要使用非空格的字符替换空格字符。这通常通过将非空格字符复制到第一个复制空间来完成。

鉴于:

+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
| P | e | a | r |   |   |   |   | f | r | u | i | t | '\0' |   
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  

您希望结果字符串如下所示:

+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
| P | e | a | r |   |   |   |   | f | r | u | i | t | '\0' |   
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
                                  |  
                      +-----------+  
                      |  
                      V   
+---+---+---+---+---+---+---+---+---+---+------+  
| P | e | a | r |   | f | r | u | i | t | '\0' |   
+---+---+---+---+---+---+---+---+---+---+------+  

您可以通过解除引用指针来指定值。

while循环后,您有:

+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
| P | e | a | r |   |   |   |   | f | r | u | i | t | '\0' |   
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
                  ^  
                  |  
str --------------+

所以你需要另一个指针跳过连续的空格:

+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
| P | e | a | r |   |   |   |   | f | r | u | i | t | '\0' |   
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+  
                      ^           ^  
                      |           |   
++str ----------------+           |  
                                  |  
non_space ------------------------+

增加目标指针src,然后复制到字符串结尾或找到空格字符:

   ++str; // Skip past the first space.
   *str++ = *non_space;

如果您使用C ++ std::string类型,则可以使用find_first_not_of方法跳过过去的空格。

std::string还有从字符串中删除字符的方法;并且std::string会根据需要移动字符。