ethanh
ethanh

Reputation: 43

Remove n characters from string c++

I'm having some trouble removing characters from a string. In my function, I have an int (n) and a string (str). I need to enter an int, then remove the first n characters of that string.

For example:

int n = 2
string str = hello

output: llo

I'm not allowed to use any string functions other than size(), otherwise I already know about erase() so I would have just used that.

I asked a friend for help, but he couldn't figure it out, either.

Here's what I have so far:

string removeFirst(string str, int n){
    //input: a string (str) and an integer (n)
    //output: a string with all but the first n characters of str

    string rv = "";

    for(int i = 0; i < str.size(); ++i){
        if(str.size() >= n){
            rv = i;
        }
    }
    return rv;
}

I'm fairly certain I need to use something along the lines of str[n], but I'm not too sure.

I know it's simple, but I'm really stuck on this.

Upvotes: 0

Views: 938

Answers (3)

user10288298
user10288298

Reputation:

Try changing the loop, like this:

string removeFirst(string str, int n) {
    
    string rv = "";

    for (int i = n; i < str.size(); i++)
    {
        rv += str[i];
    }
    
    return rv;
}

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

std::stringstream is useful to do operation with strings without directly touching that.

Example:

#include <sstream>

string removeFirst(string str, int n){
    std::stringstream ss(str);
    std::stringstream ret;
    // drop first n characters
    for (int i = 0; i < n; i++) ss.get();
    // read rest of string
    int c;
    while ((c = ss.get()) != EOF) {
        ret << static_cast<char>(c);
    }
    // return the result
    return ret.str();
}

Upvotes: 0

abhishek raj
abhishek raj

Reputation: 26

if you don't want to modify input string

string removeFirst(string str, int n){
    //input: a string (str) and an integer (n)
    //output: a string with all but the first n characters of str

    string rv = "";
    if (n >= str.size())
    {   
        return rv;
    }    
    for(int i = n; i < str.size(); ++i){
        rv+=str[i];
    }
    return rv;
}

if you want to modify your input string

void removeFirst(string &str, int n){
    //input: a string (str) and an integer (n)
    //output: a string with all but the first n characters of str

    if (n >= str.size())
    {   
        str="";
        return ;
    }    
    for(int i=0;i<str.size()-n;i++)
    {
        str[i]=str[i+n];
    }
    for(int i=str.size()-n;i<str.size();i++)
    {
        str[i]='\0';
    }
  return;
}

Upvotes: 1

Related Questions