3 Comments

  1. I tried this, but it’s giving me error C2678( binary ‘==’: no operator found which takes a left-hand operand of type ‘std::vector<std::string,std::allocator>’ (or there is no acceptable conversion) in the algorithm file!

  2. Great post!
    Can you help me with getting an output of the form
    “line 1 line 3 line 4”
    instead of “line 1line 3line 4”

    1. You can first replace ‘\n’ with ‘ ‘ and then use `std::unique()` with a lambda to remove duplicated spaces (if duplicated spaces are fine to be removed too).

      [md]
      “`
      #include
      #include

      int main ()
      {
      std::string input{“line 1\n\n\nline 3\nline 4”};

      std::cout << "input:\n" << input << "\n"; std::replace(input.begin(), input.end(), '\n', ' '); input.erase(std::unique(input.begin(), input.end(), [](char lhs, char rhs) { return lhs == rhs && lhs == ' '; }), input.end()); std::cout << "After:\n" << input << "\n"; return 0; } ``` You may also use regular expression to do so (and it is fine if the lines contains duplicated spaces): ``` #include
      #include
      #include

      int main ()
      {
      std::string input{“line 1\n\n\nline 3\nline 4”};

      std::cout << "input:\n" << input << "\n"; std::regex newlines_re("\n+"); auto result = std::regex_replace(input, newlines_re, " "); std::cout << "After:\n" << result << "\n"; return 0; } ``` [/md]

Leave a Reply

Your email address will not be published. Required fields are marked *