如何旋转std :: string? [英] How to rotate a std::string?

查看:131
本文介绍了如何旋转std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用c ++旋转字符串?

使用C ++旋转字符串

我要旋转数据。
让我说我输入单词^ HELP |在cmd中我回来:

I want to rotate the data. Lets say i enter the word ^HELP| in the cmd i get back:

^HELP|
^EELP|
^ELLP|
^ELPP|
^ELP||
^ELP|^

但这是错误的,我需要得到:

But that is wrong i need to get:

^HELP|
|^HELP
P|^HEL
LP|^HE
ELP|^H
HELP|^

其中最后一个值发送到前面,其他值发送到后面。
我使用底部的代码。我可以知道我做错了什么,为什么
它是这样做。

Where the last value is sent to the front and the other values one to the back. I used the code at the bottom. Can i please know what i am doing wrong, and why it is doing that.

       for(int j = 0;j<length;j++)
       {
           StringValue[0] = StringValue[length - 1];
           StringValue[j + 1] = StringValue[j];
           cout << StringValue<<endl;
       }

     return 0;
   }


推荐答案

使用 std :: rotate ,而不是您自己的... http:// cplusplus.com/reference/algorithm/rotate/

Use std::rotate instead of your own algo... http://cplusplus.com/reference/algorithm/rotate/

编辑。

好​​的。如果你不想使用std :: rotate使用这个algo。

它是 std :: rotate 的实现 biderrectional在MSVC2012 RC中的迭代器

template<typename Iter>
void my_rotate(Iter first, Iter mid, Iter last)
{
    typedef typename Iter::difference_type diff_t;
    diff_t shift = mid - first;
    diff_t count = last - first;
    for (diff_t factor = shift; factor;)
    {
        diff_t tmp = count % factor;
        count = factor;
        factor = tmp;
    }
    if (count < last - first)
    {
        for (; 0 < count; --count)
        {
            Iter hole = first + count;
            Iter next = hole;
            Iter next_next = next + shift == last ? first : next + shift;
            for(;;)
            {
                std::iter_swap(next, next_next);
                next = next_next;
                next_next = shift < last - next_next ? next_next + shift :
                    first + (shift - (last - next_next));
                if (next_next == hole)
                {
                    break;
                }
            }
        }
    }
}

int main()
{
    std::string StringValue = "^HELP|";
    for (size_t i = 0 ; i < StringValue.length(); ++i)
    {
        my_rotate(StringValue.rbegin(), StringValue.rbegin() + 1, StringValue.rend());
        std::cout << StringValue << std::endl;
    }
}

这篇关于如何旋转std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆