c++ - 使用 strtok 在 C++ 中进行字符串操作

标签 c++

<分区>

我正在尝试对 .gz 文件进行一些字符串操作。 并且我编写了以下代码。

char buffer[1001];
for(;gzeof(f_Handle);){
    gzread(f_Handle, buffer, 1000);
    buffer[1000] = 0;
    char* chars_array = strtok(buffer, " ");

    while(chars_array){
        cout<<chars_array << '\n';
        chars_array = strtok(NULL, " ");
    }
}

但是文件格式(.gz)在

A 1 2 3
B 2 3 5
A 4 5 6
B 34 64 123

我想知道什么时候是A或B,分别是A或B中的内容。

目前,它以下列方式打印出来

A
1
2
3
...

想法 a) 是使用 if 循环通过 chars_array 找出 A 或 B 或

b) 字符串数组代替字符指针

最佳答案

这是一个使用 std::string 和函数 substr(...) 的简单示例 它不会处理整个字符串,但您可以将其放入循环执行此操作。

#include <string>
#include <iostream>
#include <vector>

int main()
{
    std::string original = "01234567 89abc defghi j";
    std::vector< std::string > strings;

    // Find space from last index
    int lastSpaceIndex = 0;
    int spaceIndex = original.find( ' ', lastSpaceIndex );

    // Find the number of characters to split
    int numCharacters = spaceIndex - lastSpaceIndex;

    // Split string ( the second argument is the number of characters to splut out)
    std::string tokenizedString = original.substr( lastSpaceIndex, numCharacters );

    // Add to vector of strings
    strings.push_back( tokenizedString);

    // Print result
    std::cout << "Space at : " << spaceIndex << std::endl;
    std::cout << "Tokenized string : " << tokenizedString << std::endl;

    // Find the nextsubstring
    // =========================================================================
    // Need to increase by 1 since we don't want the space 
    lastSpaceIndex = spaceIndex + 1;
    spaceIndex = original.find( ' ', lastSpaceIndex );

    numCharacters = spaceIndex - lastSpaceIndex;
    tokenizedString = original.substr( lastSpaceIndex, numCharacters );

     strings.push_back( tokenizedString);

    std::cout << "Space at : " << spaceIndex << std::endl;
    std::cout << "Tokenized string : " << tokenizedString << std::endl;

    std::cout << "=====================================\n";

    for ( const auto &str : strings )
    {
        std::cout << "String : " << str << std::endl;
    }

}

输出:

Space at : 8
Tokenized string : 01234567
Space at : 14
Tokenized string : 89abc
=====================================
String : 01234567
String : 89abc

当没有更多空格时,original.find( ' ', lastSpaceIndex ) 将返回 std::npos

关于c++ - 使用 strtok 在 C++ 中进行字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21401624/

相关文章:

c++ - 打印时指向常量的指针与指向非常量的指针的行为不同

C++: 错误 "explicit specialization in non-namespace scope"

没有变量的c++派生类

python - Python 中的反修饰导出函数

c++ - 用 find() 和 string::npos 计算元音

c++ - 这种方法是否对分支预测产生积极影响?

c++ - 对 "class"的引用不明确

c++ - std::sort 中的二进制表达式错误(缺少 const)无效操作数:为什么指定比较运算符可以解决这个问题?

c++ - 段错误 C++

c++ - 错误 : undefined reference to `sqlite3_open'