简体   繁体   English

删除字符并将它们附加在字符串的末尾(C ++)

[英]Remove chars and append them in the end of the string ( C++ )

How can I erase the first N-th characters in a given string and append them in the end. 如何擦除给定字符串中的前N个字符并将其附加在末尾。 For example if we have 例如,如果我们有

abracadabra 

and we shift the first 4 characters to the end then we should get 然后将前4个字符移到末尾,然后我们应该得到

cadabraabra

Instead of earsing them from the front which is expensive there is another way. 与其从昂贵的耳朵上窃听,不如通过另一种方式。 We can rotate them in place which is a single O(N) operation. 我们可以它们旋转到位,这是一次O(N)操作。 In this case you want to rotate to the left so we would use 在这种情况下,您想向左旋转,因此我们将使用

std::string text = "abracadabra";
std::rotate(text.begin(), text.begin() + N, text.end());

In the above example if N is 4 then you get 在上面的示例中,如果N为4,则得到

cadabraabra

Live Example 现场例子

You can try an old-fashioned double loop, one char at a time. 您可以尝试一个老式的双循环,一次输入一个字符。

#include "string.h"
#include "stdio.h"

int main() {
    char ex_string[] = "abracadabra";
    int pos = 4;
    char a;
    int i, j;

    size_t length = strlen(ex_string);
    for (j = 0; j < pos; j++) {
        a = ex_string[0];
        for (i = 0; i < length - 1; i++) {
            ex_string[i] = ex_string[i + 1];
        }
        ex_string[length-1]=a;

    }
    printf("%s", ex_string);


}
string str = "abracadabra" //lets say
int n;
cin>>n;
string temp;
str.cpy(temp,0,n-1);
str.earse(str.begin(),str.begin()+n-1);
str+=temp;

Reference 参考

string::erase 字符串::: erase
string::copy 字符串::复制

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    string str;
    cin >> str;
    int number;
    cin >> number;

    string erasedString = str;
    string remainingString = str.substr(number + 1, strlen(str));

    erasedString.erase(0, number);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM