我有一个字符串,内容为“Hello foo how are you.”
我想把它改成“Hello\r\nfoo how are you.”
我想知道如何获取子字符串“Hello”,并在空格处添加\r\n,同时保留其他所有字符串。这是为了显示多行。
编辑:
我们不知道第一个子字符串的长度。我们不知道第一个子字符串将有多长。
谢谢。
<algorithm>
中使用std::find()
和在<string.h>
中使用strchr()
。如果您需要搜索任何空格而不仅仅是' '
字符,则可以使用std::find_first_of()
或strcspn()
。std::basic_string
的成员函数,<string>
中的实用程序函数,<algorithm>
中的函数以及<string.h>
中的函数,因为这些通常是您要使用的工具。string::substr (size_t pos = 0, size_t len = npos) const;
返回一个新实例化的字符串对象,其值为从调用它的指定字符串对象中获取的子字符串。
// 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的字符串部分。
// 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 所要求的。 - Andria#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)
来查找字符串" "
的第一个出现位置。