dark_matter88
dark_matter88

Reputation: 377

Insert symbol into string C++

I need to insert symbol '+' into string after its each five symbol. st - the member of class String of type string

int i = 1;
int original_size = st.size;

int count = 0;
int j;
for (j = 0; j < st.size; j++)
{
    if (i % 5)
        count++;
}

while (st.size < original_size + count)
{
    if (i % 5)
    {   
        st.insert(i + 1, 1, '+');
        st.size++;
    }
    i++;
}

return st;

I got an error in this part of code. I think it is connected with conditions of of the while-cycle. Can you help me please how to do this right?

Upvotes: 0

Views: 2335

Answers (4)

user4581301
user4581301

Reputation: 33952

Nothing no one else has done, but eliminates the string resizing and the modulus and takes advantage of a few new and fun language features.

    std::string temp(st.length() + st.length()/5, '\0');
        // preallocate string to eliminate need for resizing.

    auto loc = temp.begin(); // iterator for temp string
    size_t count = 0;
    for (char ch: st) // iterate through source string
    {
        *loc++ = ch;
        if (--count == 0) // decrement and test for zero much faster than 
                          // modulus and test for zero
        {
            *loc++ = '+';
            count = 5; // even with this assignment
        }
    }
    st = temp;

Upvotes: 0

utnapistim
utnapistim

Reputation: 27375

@AlexB's answer shows how to generate a new string with the resulting text.

That said, if your problem is to perform in-place insertions your code should look similar to this:

std::string st{ "abcdefghijk" };

for(auto i = 4; i != st.size(); i += 5) 
    st.insert(i+1, 1, '+'); // insert 1 character = '+' at position i

assert(st == "abcde+fghij+k");

Upvotes: 1

Don Reba
Don Reba

Reputation: 14051

std::string InsertEveryNSymbols(const std::string & st, size_t n, char c)
{
    const size_t size(st.size());

    std::string result;
    result.reserve(size + size / n);
    for (size_t i(0); i != size; ++i)
    {
        result.push_back(st[i]);
        if (i % n == n - 1)
            result.push_back(c);
    }
    return result;
}

You don't need a loop to calculate the length of the resulting string. It's going to be simply size + size / 5. And doing multiple inserts makes it a quadratic-complexity algorithm when you can just as easily keep it linear.

Upvotes: 0

AlexB
AlexB

Reputation: 91

If I've understood you correctly then you want to insert a '+' character every 5 chars in the original string. One way to do this would be to create a temporary string and then reassign the original string:

std::string st("A test string with some chars");
std::string temp;

for (int i = 1; i <= st.size(); ++i)
{
    temp += st[i - 1];
    if (i % 5 == 0)
    {
        temp += '+';
    }
}
st = temp;

You'll notice I've started the loop at 1, this is to avoid the '+' being inserted on the first iteration (0%5==0).

Upvotes: 3

Related Questions