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

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

本文关键字:字符串 字符 添加 串并 之间 获取 C++      更新时间:2023-10-16

我有一个字符串 你好,你好吗。

我想把它改成你好\rfoo你好吗。

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

编辑:

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

谢谢。

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

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

#include <iostream>
#include <string>
int main() {
std::string s = "Hello foo how are you.";
s.replace(s.find_first_of(" "),1,"rn");
std::cout << s << std::endl; #OUTPUTS: "Hello
#          foo how are you."
return 0;
}

这里你要用的是string::replace(pos,len,insert_str);,这个函数允许你用你的"rn"替换s中指定的子字符串。

编辑:您希望使用s.find_first_of(str)查找字符串的第一个匹配项" "

要获得子字符串,您的答案在于函数 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;
}

>UPDATE:但是它看起来与您的标题不同,您需要在不知道子字符串长度的情况下更改一些字符为此,您的答案是字符串::替换:

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>