我正在寻找一种在c ++中旋转字符串的方法.我把所有的时间花在python上,所以我的c ++ 非常生疏.
这就是我想要它做的事情:如果我有一个字符串'abcde',我希望它改为'bcdea'(第一个字符移到结尾).这是我在python中做到的方式:
def rotate(s):
return s[1:] + s[:1]
Run Code Online (Sandbox Code Playgroud)
我不知道如何在cpp中做到这一点.也许使用一系列字符?
Joh*_*itb 29
我建议std::rotate:
std::rotate(s.begin(), s.begin() + 1, s.end());
Run Code Online (Sandbox Code Playgroud)
mar*_*cog 11
这是一个将第一个字符"浮动"到字符串末尾的解决方案,有点像冒泡排序的单个迭代.
#include <algorithm>
string rotate(string s) {
for (int i = 1; i < s.size(); i++)
swap(s[i-1], s[i]);
return s;
}
Run Code Online (Sandbox Code Playgroud)
如果您希望函数就地旋转字符串:
#include <algorithm>
void rotate(string &s) {
for (int i = 1; i < s.size(); i++)
swap(s[i-1], s[i]);
}
Run Code Online (Sandbox Code Playgroud)
这是一个相对简单的方法:
void RotateStringInPlace(char buffer[])
{
// Get the length of the string.
int len = strlen(buffer);
if (len == 0) {
return;
}
// Save the first character, it's going to be overwritten.
char tmp = buffer[0];
// Slide the rest of the string over by one position.
memmove(&buffer[0], &buffer[1], len - 1);
// Put the character we saved from the front of the string in place.
buffer[len - 1] = tmp;
return;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将修改缓冲区.
算法标题中有一个标准的旋转功能.
如果您想自己做,可以尝试以下方法:
#include <iostream>
#include <string>
std::string rotate_string( std::string s ) {
if (s.empty()) return s;
char first = s[0];
s.assign(s, 1, s.size() - 1);
s.append(1, first);
return s;
}
int main() {
std::string foo("abcde");
std::cout << foo << "\t" << rotate_string(foo) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,当然,在这里使用标准库是优选的,并且在大多数情况下.
编辑#1我刚看到litb的回答.再次击败!
编辑#2我只想提一下,rotate_string函数在0长度的字符串上失败.您将收到std :: out_of_range错误.您可以使用一个简单的try/catch块来解决这个问题,或者使用std :: rotate :-)
EDIT#3如果字符串的长度为0,则返回相同的字符串.
| 归档时间: |
|
| 查看次数: |
17444 次 |
| 最近记录: |