Kristian Kamenov
Kristian Kamenov

Reputation: 347

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. For example if we have

abracadabra 

and we shift the first 4 characters to the end then we should get

cadabraabra

Upvotes: 0

Views: 247

Answers (4)

Gareth Murphy
Gareth Murphy

Reputation: 11

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);


}

Upvotes: 1

Kristian Kamenov
Kristian Kamenov

Reputation: 347

#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;
}

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

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. 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

cadabraabra

Live Example

Upvotes: 5

r-sniper
r-sniper

Reputation: 1483

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
string::copy

Upvotes: 0

Related Questions