重新排列字符C ++ [英] Rearrange character C++
问题描述
我正在尝试用C ++编写一个程序,它接受用户输入的第一个字符并将其放到最后。程序是否可以执行此操作
例如。
用户输入:'stack'
'我应该旋转多少次?'
用户输入:2
输出:'ackst'
我尝试过:
I'm trying to write a program in C++ that takes the first character of users input and puts it to the end. Do program will do that for n tines
Eg.
User Input: 'stack'
'How many times should I rotate?'
User Input: 2
Output: 'ackst'
What I have tried:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int K;
string S;
cout << "------------------------------------"<<endl;
cout << "Enter a word: ";
cin >> S;
cout << "------------------------------------"<<endl;
if(S.length() >1000)
{
cout << "------------------------------------"<<endl;
cout << "Too many characters"<<endl;
cout << "------------------------------------"<<endl;
}
if(S.length() ==1)
{
cout << "------------------------------------"<<endl;
cout << "Not enough characters"<<endl;
cout << "------------------------------------"<<endl;
}
if (S.length() <=1000 &&
S.length() !=1)
{
cout << "Times of rotation: ";
cin >> K
}
}
推荐答案
试试这个:
Try this:
if (S.length() <= 1000 && S.length() != 1)
{
cout << "Times of rotation: ";
cin >> K;
int L = S.length();
for (int ii = 0; ii < K; ii++)
{
char chFirst = S[0];
for(int i = 0; i < L - 1; i++)
S[i] = S[i+1];
S[L - 1] = chFirst;
}
cout << S;
}
一个简短的解释:
- 我们保存第一个角色
- 循环n次,其中n是旋转。
- 内循环:用第二个替换第一个字符,第二个用第三个替换,依此类推
- 将第一个字符设置为和字符串
A short explanation:
- we save the first character
- loop n- times, where n the rotation is.
- inner loop: replace the first char with the second, the second with the third and so on
- set the first character to the and of the string
在另一种方法中,您可以使用string :: substr
In an alternative approach, you could usestring::substr
#include <iostream>
#include <string>
using namespace std;
void rotate (string & s, size_t r)
{
r %= s.length();
if ( r == 0) return;
s = s.substr(r,s.length()-r) + s.substr(0,r);
}
void show_decorated(const string & message)
{
cout << "------------------------------------\n";
cout << message << '\n';
cout << "------------------------------------\n";
}
int main ()
{
int K;
string S;
cout << "------------------------------------\n";
cout << "Enter a word: ";
cin >> S;
cout << "------------------------------------\n";
if( S.length() > 1000)
{
show_decorated( "Too many characters" );
return -1;
}
if(S.length() <= 1)
{
show_decorated("Not enough characters");
return -1;
}
cout << "Times of rotation: ";
cin >> K;
rotate(S,K);
show_decorated(S);
cout << endl;
}
这篇关于重新排列字符C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!