我有一个包含 X 个单词的字符串(每个单词之间有一个空格)我必须根据用户插入的数字向左移动单词。例如:
“嗨,我叫 aviv,
”,
用户输入了2
。 “name is aviv and hi my
”我正在寻找重复的合法性,但我找不到。
感谢指导。最重要的是,我不能使用内置库
更新: 我看到有库的例子,我不能使用任何库。 所以我到目前为止所做的。 我写了一个函数,从用户那里获取一个字符串和一个数字,向左移动。 在将字符串发送到函数之前,我尝试计算需要移动的字符数。
我的输出是 - “name is avivhi my
”
关于功能:
当它得到一个没有空格的字符串时,效果很好。
这是我的代码:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
最佳答案
这里有一个提示:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
关于c++ - 如何在字符串中以圆周运动移动单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185597/