我有一个已知长度的字符数组,带有嵌入的空值;没有结尾为null。
const char * raw = "text1\0\0text2\0\0\0text3\0more text";
这样做
std::string clean(raw);
仅给我第一个字符串("text1"
),但我需要整个原始字符串。
我想要多个字符串。在这种情况下,里面有4个字符串raw.
在不知道字符串文字的实际大小的情况下,您将无法执行此任务。如果知道大小,则可以使用构造函数
basic_string(const charT* s, size_type n, const Allocator& a = Allocator());
或相应的方法 assign
在这里,第二个参数指定将在字符串中复制的s的字符数。
如果长度是已知的,那么您可以简单地写
std::string clean( raw, n );
或者
std::string clean;
clean.assign( raw, n );
编辑:当您更改了原始消息后,我将附加我的帖子。您可以按以下方式拆分文字
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
const char * s = "text1\0\0text2\0\0\0text3\0more text";
size_t n = 30;
std::istringstream is( std::string( s, 30 ) );
std::vector<std::string> v;
std::string word;
while ( std::getline( is, word, '\0' ) ) if ( !word.empty() ) v.push_back( word );
for ( const std::string &s : v ) std::cout << s << std::endl;
}
输出是
text1
text2
text3
more text
如果您有四个不同的字符串,则可以编写
#include <iostream>
#include <sstream>
#include <string>
int main()
{
const char * s = "text1\0\0text2\0\0\0text3\0more text";
size_t n = 30;
std::istringstream is( std::string( s, 30 ) );
std::string word1, word2, word3, word4;
while ( std::getline( is, word1, '\0' ) && word1.empty() );
while ( std::getline( is, word2, '\0' ) && word2.empty() );
while ( std::getline( is, word3, '\0' ) && word3.empty() );
while ( std::getline( is, word4, '\0' ) && word4.empty() );
for ( const std::string &s : { word1, word2, word3, word4 } ) std::cout << s << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句