sel*_*bie 5 c c++ string formatting string-formatting
是否有一个通用的C/C++库(或常用技术)用于获取输入文本的行并将单词拆分为单独的行.每行输出具有最大宽度,而单词不跨行分割.崩溃或保留的空白是可以的.必须保留标点符号.小而紧凑的图书馆是首选.
我可以轻松地度过一个下午把一些东西放在一起起作用,但是想知道是否有一些共同点,所以我不会重新发明轮子.如果输入行可以包含格式说明符以指示输出行的缩进级别,则加分.
示例输入:"Shankle鼓腌牛肉,夹头火鸡鸡肉猪肉牛排牛排牛排香肠.尾部短腰肩球尖,下颚鼓臀.尾舌球尖肉饼,bresaola短腰三尖端肥猪腰里脊牛腿biltong.鹿肉短腰里ou.
示例输出(目标宽度= 60)
123456789012345678901234567890123456789012345678901234567890 Line added to show where 60 is
Shankle drumstick corned beef, chuck turkey chicken pork
chop venison beef strip steak cow sausage. Tail short loin
shoulder ball tip, jowl drumstick rump. Tail tongue ball tip
meatloaf, bresaola short loin tri-tip fatback pork loin
sirloin shank flank biltong. Venison short loin andouille.
Run Code Online (Sandbox Code Playgroud)
这是我的方法,它当然不是最快的,但我试图使其尽可能可读。结果和你的例子是一样的。
#include <iostream>
#include <string>
std::string splitInLines(std::string source, std::size_t width, std::string whitespace = " \t\r")
{
std::size_t currIndex = width - 1;
std::size_t sizeToElim;
while ( currIndex < source.length() )
{
currIndex = source.find_last_of(whitespace,currIndex + 1);
if (currIndex == std::string::npos)
break;
currIndex = source.find_last_not_of(whitespace,currIndex);
if (currIndex == std::string::npos)
break;
sizeToElim = source.find_first_not_of(whitespace,currIndex + 1) - currIndex - 1;
source.replace( currIndex + 1, sizeToElim , "\n");
currIndex += (width + 1); //due to the recently inserted "\n"
}
return source;
}
int main() {
std::string source = "Shankle drumstick corned beef, chuck turkey chicken pork chop venison beef strip steak cow sausage. Tail short loin shoulder ball tip, jowl drumstick rump. Tail tongue ball tip meatloaf, bresaola short loin tri-tip fatback pork loin sirloin shank flank biltong. Venison short loin andouille.";
std::string result = splitInLines(source , 60);
std::cout << result;
return 0;
}
Run Code Online (Sandbox Code Playgroud)