【发布时间】:2018-10-15 13:42:33
【问题描述】:
我有一个包含 X 个单词的字符串(每个单词之间有一个空格)我必须根据用户插入的数字以圆周运动将单词向左移动。例如:
"hi my name is aviv and",
用户输入了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;
}
【问题讨论】:
-
将单词存储在数组中并移动它们的索引。
-
到目前为止你有什么尝试?发布您的代码。
标签: c++ string algorithm rotation stdstring