使用Strtok在C 中进行弦乐操作
String manipulations in C++ using strtok
我正在尝试从.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或B中的内容。
目前,它以followng的方式打印出来
A
1
2
3
...
想法a)是使用if loop通过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
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?
- 使用Strtok在C 中进行弦乐操作
- 分段故障 C++ 最有可能在 strtok 操作中