简体   繁体   English

从字符串c ++中删除n个字符

[英]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 ).在我的函数中,我有一个 int ( n ) 和一个 string ( str )。 I need to enter an int, then remove the first n characters of that string.我需要输入一个整数,然后删除该字符串的前n字符。

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.我不允许使用除size()之外的任何字符串函数,否则我已经知道erase()所以我会使用它。

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.我相当确定我需要使用str[n]类似的东西,但我不太确定。

I know it's simple, but I'm really stuck on this.我知道这很简单,但我真的坚持这一点。

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

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

std::stringstream is useful to do operation with strings without directly touching that. std::stringstream可用于在不直接接触字符串的情况下对字符串进行操作。

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

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

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