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 | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
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.