Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to remove newlines from a string C++

3 Answers

0 votes
#include <string>
#include <iostream>
#include <algorithm>

std::string removeNewlines(std::string s) {
    s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
    s.erase(std::remove(s.begin(), s.end(), '\r'), s.end());
    
    return s;
}

int main() {
    std::string s = "c++\n java\r python\ngo\n";

    s = removeNewlines(s);

    std::cout << s << "\n";
}



/*
run:

c++ java pythongo

*/

 



answered 4 hours ago by avibootz
0 votes
#include <string>
#include <iostream>
#include <algorithm>

std::string removeNewlines(const std::string& s) {
    std::string out;
    out.reserve(s.size());

    for (char ch : s) {
        if (ch != '\n' && ch != '\r')
            out.push_back(ch);
    }
    
    return out;
}


int main() {
    std::string s = "c++\n java\r python\ngo\n";

    s = removeNewlines(s);

    std::cout << s << "\n";
}


/*
run:

c++ java pythongo

*/

 



answered 4 hours ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>

std::string normalize_whitespace(const std::string& s) {
    std::string out;
    out.reserve(s.size());

    bool lastWasSpace = false;

    for (char ch : s) {
        if (ch == '\n' || ch == '\r' || std::isspace(static_cast<unsigned char>(ch))) {
            if (!lastWasSpace) {
                out.push_back(' ');
                lastWasSpace = true;
            }
        } else {
            out.push_back(ch);
            lastWasSpace = false;
        }
    }

    // Trim trailing space
    if (!out.empty() && out.back() == ' ')
        out.pop_back();

    return out;
}

int main() {
    std::string s = "c++\n   java\r   python\ngo\n";
    
    std::cout << normalize_whitespace(s) << "\n";
}


/*
run:

c++ java python go

*/

 



answered 4 hours ago by avibootz
...