C++ Remove new line from multiline string

前端 未结 12 2284
暗喜
暗喜 2020-12-08 06:14

Whats the most efficient way of removing a \'newline\' from a std::string?

相关标签:
12条回答
  • 2020-12-08 06:35

    If its anywhere in the string than you can't do better than O(n).

    And the only way is to search for '\n' in the string and erase it.

    for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);
    

    For more newlines than:

    int n=0;
    for(int i=0;i<s.length();i++){
        if(s[i]=='\n'){
            n++;//we increase the number of newlines we have found so far
        }else{
            s[i-n]=s[i];
        }
    }
    s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines
    

    It erases all the newlines once.

    0 讨论(0)
  • 2020-12-08 06:39
     std::string some_str = SOME_VAL;
     if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
      some_str.resize( some_str.length()-1 );
    

    or (removes several newlines at the end)

    some_str.resize( some_str.find_last_not_of(L"\n")+1 );
    
    0 讨论(0)
  • 2020-12-08 06:40

    Another way to do it in the for loop

    void rm_nl(string &s) {
        for (int p = s.find("\n"); p != (int) string::npos; p = s.find("\n"))
        s.erase(p,1);
    }
    

    Usage:

    string data = "\naaa\nbbb\nccc\nffffd\n";
    rm_nl(data); 
    cout << data; // data = aaabbbcccffffd
    
    0 讨论(0)
  • 2020-12-08 06:41

    All these answers seem a bit heavy to me.

    If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?

    for (int i = 0; i < str.length();i++) {
       if (str[i] == '\n') {
          str[i] = ' ';
       }
    }
    

    There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.

    0 讨论(0)
  • 2020-12-08 06:44

    If the newline is expected to be at the end of the string, then:

    if (!s.empty() && s[s.length()-1] == '\n') {
        s.erase(s.length()-1);
    }
    

    If the string can contain many newlines anywhere in the string:

    std::string::size_type i = 0;
    while (i < s.length()) {
        i = s.find('\n', i);
        if (i == std::string:npos) {
            break;
        }
        s.erase(i);
    }
    
    0 讨论(0)
  • 2020-12-08 06:45

    You should use the erase-remove idiom, looking for '\n'. This will work for any standard sequence container; not just string.

    0 讨论(0)
提交回复
热议问题