如何在C++中的空格处换行
How do you wrap text at a space in C++
我正在尝试制作一个文本包装函数,该函数将在包装之前接收一个字符串和要计数的字符数量。如果可能的话,我想通过寻找以前的空间并在那里包装来避免任何单词被切断。
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
string textWrap(string str, int chars) {
string end = "n";
int charTotal = str.length();
while (charTotal>0) {
if (str.at(chars) == ' ') {
str.replace(chars, 1, end);
}
else {
str.replace(str.rfind(' ',chars), 1, end);
}
charTotal -= chars;
}
return str;
}
int main()
{
//function call
cout << textWrap("I want to wrap this text after about 15 characters please.", 15);
return 0;
}
将 std::string::at 与 std::string::rfind 结合使用。替换第 location
个字符右侧的空格字符的部分代码是:
std::string textWrap(std::string str, int location) {
// your other code
int n = str.rfind(' ', location);
if (n != std::string::npos) {
str.at(n) = 'n';
}
// your other code
return str;
}
int main() {
std::cout << textWrap("I want to wrap this text after about 15 characters please.", 15);
}
输出为:
我要包装
请在此文本后大约 15 个字符。
对字符串的其余部分重复此操作。
有一种比自己搜索空间更简单的方法:
Put the line into a `istringstream`.
Make an empty `ostringstream`.
Set the current line length to zero.
While you can read a word from the `istringstream` with `>>`
If placing the word in the `ostringstream` will overflow the line (current line
length + word.size() > max length)
Add an end of line `'n'` to the `ostringstream`.
set the current line length to zero.
Add the word and a space to the `ostringstream`.
increase the current line length by the size of the word.
return the string constructed by the `ostringstream`
我在那里留下了一个陷阱:处理行尾的最后一个空格。
相关文章:
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 如何在C++中的空格处换行
- QRegExp 删除换行符和多个空格
- 在换行的命令行中,取消//后面的空格的合理性
- 如何将换行符按钮更改为空格以完成从输入流的读取
- 如何检查字符串是否包含空格/制表符/换行符(任何空白内容)?
- 使用 getchar() 输入字符的最有效方法,就像 cin 中没有换行符和空格字符一样C++
- 确定单词后跟的是空格还是换行符
- C++:抓取文件的每个字符,忽略换行符和空格
- 如何在C++中将空格和换行符分隔的整数读取到2D数组中
- 如何从包含空格和换行符的文本文件中提取特定数据
- 从文件中读取空格分隔的数字,直到换行符
- Clang:在单行注释中以空格分隔的反斜杠和换行符
- 用cin处理空格并返回(换行符)
- 读取由空格或换行符分隔的输入.