【问题标题】:How to get substring in C++ and add character in between string如何在 C++ 中获取子字符串并在字符串之间添加字符
【发布时间】:2017-08-12 05:17:42
【问题描述】:

我有一个字符串 Hello foo 你好吗。

我想把它改成你好\r\nfoo 你好吗。

我想知道获取子字符串 Hello add \r\n 代替空格并按原样添加所有其他字符串的方法。这是为了显示多线。

编辑:

我们不知道第一个子字符串的长度。我们不知道第一个子字符串有多长。

谢谢。

【问题讨论】:

    标签: c++ string substring multiline


    【解决方案1】:

    不是一个完整的答案,因为这看起来像是家庭作业,但您可以使用的其他方法包括<algorithm> 中的std::find()<string.h> 中的strchr()。如果您需要搜索任何空格而不仅仅是' ' 字符,您可以使用std::find_first_of()strcspn()

    以后,我会查看以下文档:std::basic_string 的成员函数、<string> 中的实用函数、<algorithm> 中的函数以及<string.h> 中的函数,因为这些将通常是您必须使用的工具。

    【讨论】:

    • 我应该添加一个附录。您可能经常将正则表达式库用于此类事情。
    【解决方案2】:
    #include <iostream>
    #include <string>
    
    int main() {
      std::string s = "Hello foo how are you.";
      s.replace(s.find_first_of(" "),1,"\r\n");
      std::cout << s << std::endl; #OUTPUTS: "Hello
                                   #          foo how are you."
      return 0;
    }
    

    你要在这里使用的是string::replace(pos,len,insert_str);,这个函数可以让你用你的"\r\n"替换s中的指定子字符串。

    编辑:您想使用s.find_first_of(str) 来查找字符串" " 的第一次出现

    【讨论】:

    • 但是为此我应该知道第一个子字符串有多少个字符。场景是我们不知道第一个子字符串中的字符数。
    【解决方案3】:

    要获得子字符串,您的答案在于函数string::substr

    string::substr (size_t pos = 0, size_t len = npos) const;
    
    1. pos 参数是要复制为子字符串的第一个字符的索引。
    2. len 参数是要包含在从索引开始的子字符串中的字符数。

    返回一个新实例化的字符串对象,其值是调用它的指定字符串对象的子字符串。

    // Example:
    #include <iostream>
    #include <string>
    
    int main () {
      std::string str1= "Hello Stack Overflow";
      std::string str2 = str.substr (0,5); // "Hello
      std::cout << str2 << std::endl; // Prints "Hello"
    
      return 0;
    
    }
    

    更新:但是它看起来与您的标题不同,您需要的是在不知道子字符串长度的情况下更改一些字符

    为此,您的答案是string::replace

    string& replace (size_t pos,  size_t len,  const string& str);
    

    替换从索引 pos 开始到索引 len 的字符串部分。

    1. pos 参数是要替换的第一个字符的索引。
    2. len 参数是从索引开始要替换的字符数。
    3. str 字符串参数来替换它。

        // Example
        int main() 
           std::string str = "Hello Stack Overflow.";
           std::string str2 = "good";
           str.replace(6, 4, str2);   // str = "Hello goodStackOverflow"
           return 0;
        }
    

    在某些编译器中,您可能不需要添加它,但您需要包含字符串标头以确保您的代码可移植和可维护:

    #include <string>
    

    【讨论】:

    • string::substr 用于获取子字符串而不是替换子字符串,这是一个低效的答案,坦率地说不是OP所要求的。
    • 你所做的只是得到子字符串"Hello",你从来没有在字符串之间添加一个字符。
    • 你仍然没有回答问题,你只是在复制我的答案。
    • @chbchb55 只要我们不知道提问者指的是什么子字符串,我们就无法找到答案。据我所知,我已经让读者知道如何完成标题中的两个任务with sources。您正在将练习交给拼盘中的提问者,我正在为他提供执行此操作所需的工具。
    • 他说"I wanted to know the way to get the substring Hello add \r\n **in place of space** and add all other strings as they are."
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2011-08-07
    相关资源
    最近更新 更多