I would always do if I wanted to insert 'a' into the beginning of the string. reverse(s.begin(), s.end());
s += 'a';
reverse(s.begin(), s.end());
Is there a built-in function to insert a character in the beginning of a string?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
8 | Dominater069 | 154 |
8 | nor | 154 |
I would always do if I wanted to insert 'a' into the beginning of the string. reverse(s.begin(), s.end());
s += 'a';
reverse(s.begin(), s.end());
Is there a built-in function to insert a character in the beginning of a string?
Название |
---|
You can use insert(index,string) to insert string at any position of your string.
Thanks, but do you know the time complexity of each? The built-in method and my method.
Both methods are O(n) which is highly not recommended. Try to use deque instead. like:
A simple code that takes input from a string and then places an F before the string:
I hope this helped!
Edit: The reason your method is O(n) is that you reverse the whole string which literally takes O(n). The method that the builtin insert takes O(n) is because when you insert a character, you need to shift all other characters in the memory block which takes O(n). But, deque allocates memory for both ends which causes an insertion/deletion time at beginning/ending to be O(1). But take care that deque has a little bit more constant time than string and vector(But it will not be that obvious).
Thanks! BTW, you can just do
for(auto i: dq) { cout << i << " "; }
You are welcome!
In the same vein, you can even do
and
and avoid writing loops completely.
Edit: with spaces, it would be
Thanks!
The simplest thing is to write s = 'a' + s. I'm not sure what is the complexity, but since it is just copying string I believe it cannot be bigger than linear.
It's O(n)
I want it to put the character in the beginning of the string and not the end of the string. Thanks tho
This does put it at the begging of the string. Try it.
Oh... That was my bad. I thought that you wrote s = s + 'a'. and not s = 'a' + s; Thanks!
General TIP : Complexity of adding char at the end is O(n) if you are doing s = s + 'a' and O(1) if you are doing s += 'a'.
Really? Do think about allocating space for a new buffer 1 byte more than the existing one and copying all characters of the string into the buffer then storing the character 'a' at the end.