How to create a new string without spaces from another string using a loop

I suggest to not use a hand crafted loop. You can use std::copy_if in combination with a lambda expression to formulate your condition. This will be more stable than your implementation (what happens if the length of your string s exceeds the capacity of an int?). I think it also enhances the readability.

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string s = "here is some text";
    std::string t = "";
    auto comp = [&](const char c) { return std::isalpha(c); };
    std::copy_if(s.begin(), s.end(), std::back_inserter(t), comp);

    std::cout << t << std::endl;
}

You have undefined behavior in your loop, as you insert into a std::string using its operator[] without making sure it has the right size. You can instead use

t.push_back(s[i]);

which not only inserts a char, but also makes sure the internal buffer is (re-)allocated when it's too small for the new string.

Note further that you don't really need the count variable. std::string always keeps track of its length, so t.size() will always yield the value of your current count (once you fix the UB of course).

As an aside, copying the parts of a sequence that match a certain criterion is a common task, and there exists a specific library template that does exactly this and frees you from a hand-crafted loop:

#include <algorithm>

std::copy_if(s.cbegin(), s.cend(), std::back_inserter(t),
     [](char c){ return std::isalpha(c); });

Finally, also note the comment by @MatthieurFoltzer on the behavior of std::isalpha, which might be worth taking into account.


t[count]+=s[i];

This doesn't work like that. With this you can change existing characters of the string. But since your string is empty, that causes undefined behavior. To append to the string, change that line to this instead:

t += s[i];

And it'll print the desired output of hereissometext. You can find the documentation of the += operator for strings here.

Tags:

C++

String

Loops