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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
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.