弦旋转r个位置
string rotation by r places
我试图用'r'位置旋转我的字符串,但面临一些问题。以下是我的代码(函数)。请帮助。例如:r=3
之后的hello coding.
应该变成ng.hello codi
。
void fnc(){
char a[100],key;
int n,r,i,t=1,total=0,count,x;
cin>>n; //no. of test cases
while(t<=n){
cin>>r; //no. of rotations
cin.get();
cin.get(a,100);
for(i=0; a[i]!= ' '; i++){
//cout<<a[i];
total++;
}
cout<<total;
for(i=0; i<r; i++){
key = a[total-1];
cout<<"key: "<<key<<endl;
for(i=total-2; i>=0; i--){
a[i+1] = a[i];
}
a[0] = key;
}
for(i=0; a[i]!= ' '; i++){
cout<<a[i];
}
///cout<<a<<endl;
t++;
}
}
这里有一种只使用迭代器的方法:
#include <string>
#include <iostream>
using namespace std;
int mod(int a, unsigned int b) {
int ret = a % b;
return ret>=0 ? ret : b + ret;
}
string rotate(const string sentence, int rotation) {
rotation = mod(rotation, sentence.size());
string rotatedSentence;
for(auto itr=sentence.begin(); itr < sentence.end(); ++itr) {
if (distance(sentence.begin(), itr) < rotation) {
rotatedSentence.push_back(*(itr + sentence.size() - rotation));
} else {
rotatedSentence.push_back(*(itr - rotation));
}
}
return rotatedSentence;
}
int main() {
const string sentence = "hello coding.";
cout << sentence << endl;
cout << rotate(sentence, 3) << endl; //prints ng.hello codi
return 0;
}
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 与互斥锁相比,旋转锁可以保证上下文切换
- 给定方向和位置如何使用 GLM 计算旋转矩阵
- 在旋转 cv::Mat 而不裁剪后,将 cv::RotatedRect 移动到相同的位置
- 无法从非原点的其他位置旋转对象
- OpenCV 计算相机位置和旋转
- 将OpenCV旋转和平移矢量转换为XYZ旋转和XYZ位置
- 球物理-通过旋转修改球的X/Y位置
- 如何根据鼠标位置旋转精灵
- 根据鼠标的位置旋转我的形状的角度
- 如何将连接接头的位置转换为相对增量旋转
- OpenGL - 旋转玩家位置以面对鼠标指针
- 从全局位置/旋转/缩放更新局部位置/旋转/缩放
- opencv:使用旋转和平移向量设置模型位置
- 精灵旋转偏移不会停留在它所属的位置。(SDL)
- 弦旋转r个位置
- 获取当前旋转和位置坐标
- 关节位置到旋转
- 当图像在c++中处于垂直位置时,如何停止不断旋转