The task is simple - there is a string, for example std :: string ("sfsfsgsdshhdfjj"), you need to insert the symbol "-" through every second character. I don’t understand how to implement this, please tell me.
3 answers
The easiest way, perhaps, is to create a new line and stuff all this stuff there, character by character.
Sort of
string s("sfsfsgsdshhdfjj"); string d; for(auto c: s) { d += c; d += '-'; } Update As it turned out, I did not quite correctly understand that a hyphen was necessary after two to a third ... Something like this:
string d; for(size_t i = 0; i < s.length(); ++i) { d += s[i++]; if (i < s.length()) { d += s[i]; d += '-'; } } - I would add:
d.reserve(s.length()*2-1)- Monah Tuk - Yes, I agree, somewhat faster. Here - ideone.com/Jmlwde - comparison with redundancy, without and with the method of insertion. - Harry
- oneIn general, the fastest one is: ideone.com/B4C7xG explaining why:
operator[]does not perform any checks at all, andoperator+=does it. At least - suddenly the capacity has been exhausted, which means you need to add memory, as it were. The rule of the smallest overhead projector, along with the least surprise. Your version also contains an error: always added-at the end, although it should not at all. Proof: ideone.com/VbE5RW - Monah Tuk
The @Harry solution is fast, and if you have a memory of two buffers at once, then you can either like yours or this (additional O (1) memory):
// Резервируем память, что бы исключить реаллокации при вставке s.reserve(s.length()*3/2); for (size_t i = 2; i < s.length(); i+=2) s.insert(i++, 1, '-'); // инкремент тут нужен, что бы уйти с только что вставленного '-' Minus: it is slow due to the fact that every time you insert you need to do memmove / memcpy for the remaining characters.
Check: http://ideone.com/SAQCkz
UPD : corrected under the condition (every second character)
UPD2 : the most (for now?) Quick version (additional memory O (n)):
string str; str.resize(s.length() * 3/2); size_t size = 0; for (size_t i = 0; i < s.length(); ++i) { str[size++] = s[i++]; if (i < s.length()) { str[size++] = s[i]; if (i != s.length() - 1) str[size++] = '-'; } } // ;-) str.resize(size); Check: http://ideone.com/B4C7xG
Comparison: http://ideone.com/VbE5RW
Here is what I came up with:
std::string tempStr; for (size_t i(0), j(0); i < tempStr.size(); i++, j++) { if (j > 1) { tempStr.insert(i, "-"); j = -1; } } - And so you need to insert every third? I misunderstood you. But the principle does not change :) You have the main thing - insertion in the middle - the operation is expensive ... - Harry
- I have corrected my decision, see here - ideone.com/Jmlwde - and yours is there, too, with a time check. And note that you have something like O (N ^ 2), so if the length of the string is 10 times longer, ideone swears - the time limit is exceeded ... - Harry
- @Harry - yes, everything is fine, and so it works, thanks to you for the option - Duracell
"Правка никак не делает сообщения более простым к прочтению, не упрощает его поиск, точность или доступность. Изменения абсолютно излишни или явно ухудшают читаемость."- Denis