简体   繁体   English

QByteArray:如何在其中搜索字符

[英]QByteArray: how to search a character in it

Starting from a QByteArray, I'd like to search "\\n" char inside my QByteArray and join all the characters from the beginning up to "\\n" and save them in a QString; 从QByteArray开始,我想在我的QByteArray中搜索“ \\ n” char,并将所有字符从头到尾连到“ \\ n”并将它们保存在QString中; after that, I'd pass to the following bytes up to the next "\\n" and save these into a new QString 之后,我将以下字节传递到下一个“ \\ n”并将其保存到新的QString中

QByteArray MyArray= (all data from my previous process);
quint16 ByteArrayCount = MyArray.count(); // number of bytes composing MyArray
quint16 mycounter;
QString myString;
while (mycounter < ByteArrayCount)
{
    if(MyArray[mycounter] != "\n")
      myString.append(MyArray[mycounter]);
    mycounter++;
}

This to append all bytes preceeding a new line; 这将在所有行之前附加所有字节; my problem is how to evaluate MyArray[counter], since I'm not able to check every byte when the counter increases. 我的问题是如何评估MyArray [counter],因为当计数器增加时,我无法检查每个字节。

Solution? 解?

You could save yourself the trouble and simply: 您可以省去麻烦,只需:

QString s(myArray);
QStringList resultStrings = s.split('\n');

This will give you a list of strings split for every new line character, which is what you sound like you want to do. 这将为您提供一个为每个换行符分割的字符串列表,这听起来像您想做的。

Also, not to belabor the point, but you don't initialize your counter, and you really should ;) 另外,不要太在意这一点,但是您不要初始化计数器,因此您应该 ;;)

Here is simple example of using function hello 这是使用函数hello的简单示例

QString str = "ooops\nhello mama\n daddy cool";
QByteArray bta;
bta.append(str);
for(quint16 index = bta.indexOf('\n'); 
            index != -1; 
            index = bta.indexOf('\n', index+1)) {
   /**
    * Do something with index
    **/
}

But according to your question there is not so clear when you say that you "not able to check every byte". 但是根据您的问题,当您说“无法检查每个字节”时,并不清楚。 If you know diapasons of available mem, you can use raw data with: 如果您知道可用内存的原因,则可以将原始数据用于:

const char * ptr = MyArray.constData();

and use custom validators: 并使用自定义验证器:

while(ptr){
    if(valid(ptr) && ptr == '\n') {
        /**
         * do something ...
         **/
    }
    ptr++;
}

ow and also in C/C++: ow以及在C / C ++中:

"\n" != 'n'

because "\\n" - is const C string(char[2]) containing \\n and EOF('\\0') and '\\n' - is just simple C char; 因为“ \\ n”-是包含\\ n和EOF('\\ 0')和'\\ n'的const C字符串(char [2])-只是简单的C char;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM