如何在 C++ 中获取子字符串并在字符串之间添加字符

How to get substring in C++ and add character in between string

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

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

我想知道如何获取子字符串 Hello 添加 \r\n 代替 space 并按原样添加所有其他字符串。这是为了显示多行。

编辑:

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

谢谢。

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

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

Returns 一个新实例化的字符串 object,其值为调用它的指定字符串 object 的子字符串。

// 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 goodWhosebug"
       return 0;
    }

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

#include <string>
#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) 查找字符串 " "

的第一次出现

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

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