简体   繁体   中英

How can I copy a string variable to another character by character without defining size of target variable?

I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But as the size of the string in C++ is calculated dynamically as

string k = "Hello";
string l = "Hello World";
string m = k;
m = l;

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b .

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But in this case, my program is crashing and saying String subscript out of range .

Why not in this case the size of variable b is increasing? What is the cause of the error and how can I achieve this without mentioning the size of any variable?

If you must, you can use push_back :

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b.push_back(a[i]);

or even 1

string a = "Hello";
string b;
for (auto c : a)
    b.push_back(c);

But why?

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


1 But don't do this if a is changed in any way: the underlying iterators will be invalidated.

You can simply use the += operator:

for (auto el : a){
    b += el;
}

The std::string::operator+= has an overload that accepts character.

Size of the string is dynamic, but it not changed automaticaly as you expect. operator[] only return i-th element, if current size of a string is less than i, it fill fail. It's up to you to make sure size of a string is big enough.

If you couldn't resize string in advance you can query size, increase it by one, ask string to resize, and set last char.

This is how push_back method works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM