有一个字符串如何从第一个' /r/n/r/n '得到它的内容,直到2行从字符串结束

Having a string how to get its contents from first `/r/n/r/n` until 2 lines from string end?

本文关键字:字符串 直到 结束 2行 有一个 第一个      更新时间:2023-10-16

我尝试在c++中创建简单的文件上传服务。我将所有用户请求体作为一个大字符串。用户可以上传任何类型的数据。我只需要从请求正文字符串中获取用户文件内容。

因此,例如,现在我有下一个代码与我的服务API提供商工作:

std::cout << "Request body: " << request->body << std::endl << "Request size: " <<  request->body.length() << std::endl;

,这将打印为:

Request body: ------WebKitFormBoundaryAZlJcLinxYi6OCzX
Content-Disposition: form-data; name="datafile"; filename="crossdomain.xml"
Content-Type: text/xml
я╗┐<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-
omain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>
------WebKitFormBoundaryAZlJcLinxYi6OCzX--
Request size: 411

所以我需要从请求->体(这是字符串)从第一个/r/n/r/n直到最后一行-2行的所有数据。如何做这样的事情与字符串在c++ ?

这不是最优雅的方法,但是一种选择是这样做:

std::string contents = /* ... get the string ... */
/* Locate the start point. */
unsigned startPoint = contents.find("rnrn");
if (startPoint == string::npos) throw runtime_error("Malformed string.");
/* Locate the end point by finding the last newline, then backing up
 * to the newline before that.
 */
unsigned endPoint = contents.rfind('n');
if (endPoint == string::npos || endPoint == 0) throw runtime_error("Malformed string.");
endPoint = contents.rfind('n', endPoint - 1);
if (endPoint == string::npos) throw runtime_error("Malformed string.");
/* Hand back that slice of the string. */
return std::string(contents.begin() + startPoint, contents.begin() + endPoint);

您可以使用正则表达式。这个页面有一些不错的c++示例:http://www.math.utah.edu/docs/info/libg++_19.html