Malcom98.
Malcom98.

Reputation: 65

Adding character to a string

I got one problem.

#include <iostream>

using namespace std;

int main(){
    string word;
    cout << "Enter word: ";
    cin >> word;
    int i = 0;
    do {
        if (word.at(i) == 'a') {
            word.at(i) += 'r';
        }
        i++;
    } while(i < word.size());
    cout << word << endl; 
    return 0;
}

All I want to do, is if input is for example: racket, the output should be rarcket. In other words, each time character 'a' is located, the program should add character 'r' to it.

I think the program gets the ASCII code value of each letter and then it does addition operation. It gives me some strange letter.

Upvotes: 0

Views: 1399

Answers (7)

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

For starters you should include the header <string> explicitly

#include <string>

because according to the C++ Standard it is not necessary that the header <iostream> includes the header <string>.

You could use the method insert of the class std::string as others are suggesting. However this approach is inefficient because there can be many moves of substrings and reallocations of the memory occupied by the string.

In my opinion a straightforward approach will be more efficient.

Here is a demonstrative program:

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

int main()
{
    std::string word;

    std::cout << "Enter word: ";

    std::cin >> word;

    std::string::size_type n = std::count(word.begin(), word.end(), 'a');

    if (n)
    {
        auto m = word.size();
        word.resize( m + n);

        for (auto i = m; n != 0; )
        {
            if (word[--i] == 'a')
            {
                word[i + n--] = 'r';
            }
            word[i + n] = word[i];
        }
    }

    std::cout << word << std::endl;

    return 0;
}

Upvotes: 0

when you do

 word.at(i) = 'r'; 

you are actually changing the character at position i to a different value.

if you need to append/add a string at a given index in the word object then do

word.insert(1, "!");

example:

std::string word{"HelloXoce"};

std::cout << "Word: " << word << std::endl;
word.at(0) = 'X';
std::cout << "Word: " << word << std::endl;
word.insert(1, "!");
std::cout << "Word: " << word << std::endl;

Upvotes: 0

user5821508
user5821508

Reputation: 332

insert after first occurrence

auto search = 'a';
auto insert = 'b';
for(auto i = word.begin(), e = word.end(); i < e; ++i)
  if(*i == search) {
    word.insert(i + 1, insert);
    return;
  }

insert after each occurrence

auto search = 'a';
auto insert = 'b';
for(auto i = word.begin(), e = word.end(); i < e; ++i)
  if(*i == search) {
    i = word.insert(i + 1, insert);
    e = word.end();
  }

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

word.at(i) += 'r'; is changing the character at position i to a different value. It is not inserting r into the string.

If char is signed on your platform, then depending on your encoding, the behaviour of your program is undefined as adding 'r' to 'a' might overflow a signed type! 'a' and 'r' are simply numeric literals of char type. This notation is provided for convenience in order to make code clear and portable.

If you want to insert an actual character then use std::string::insert:

word.insert(word.begin() + ++i, 'r');

would do it, I've taken care to increment i again to skip over the character just added.

Reference: http://en.cppreference.com/w/cpp/string/basic_string/insert

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

if(word.at(i)=='a'){
    word.at(i)+='r';
}

The above code does not do what you think it should. It adds the numeric representation of 'a' with 'r' and stores it at index i. Assuming the result fits into the type of char on your platform.

You can std::string::insert into a specific position in the string, but its probably better to just use an new string: - You may copy each character of the string to another string (appending an extra character on the fly).

std::string word;
std::string newWord;
std::cout << "Enter word: ";
std::cin >> word;
for(int i = 0; i < word.size(); i++)
    newWord += word[i];
    if(word[i] == 'a')
        newWord += 'r';
}
std::cout << newWord << std::endl; 

EDIT: As noted, the above works, because std::string has an overloaded += operator for char

Upvotes: 0

Boris
Boris

Reputation: 368

You should use string::insert.

Here is the code that will work for your example:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string word;
    cout << "Enter word: ";
    cin >> word;
    int i = 0;
    do {
        if (word.at(i) == 'a') {
            word.insert(i + 1, "r");
        }
        i++;
    } while (i<word.size());
    cout << word << endl;
    return 0;
}

Upvotes: 1

Christian Rau
Christian Rau

Reputation: 45948

You are not inserting anything into your string. Instead you actually call the += operator of the character element, not the one of the string (which can only append at the end anyway).

What you actually want to do is insert an element into the string. The easiest way to do that in your example would be something like replacing

word.at(i)+='r';

with

word.insert(word.begin()+(++i), 'r');

which inserts an 'r' behind the 'a' you found.

However, notice that inserting characters in this way might invalidate any iterators into the string due to possible reallocation. This isn't a problem in your case, since you use an index-based iteration and check against the (possibly increased) size of the string in each iteration, but it is something worth to keep in mind.

Upvotes: 2

Related Questions