C++中提取字符串子串的常見方法包括使用std::string的substr、find等成員函數,也可以利用C風格的指針數組配合strtok函數實現。本文演示如何使用指針數組從字符串中提取子字符串。
strtok用於將字符串按指定分隔符分割為多個token(標記)。函數原型:
char *strtok(char *str, const char *delim);
delim中任意字符均可作為分隔符由於strtok返回字符指針,可用指針數組char *tokens[MAX]保存每個子串的起始地址。
#include <stdio.h>
#include <string.h>
int main(void) {
char str[] = "- This, a sample string.";
char *pch;
char *tokens[20]; // 指針數組存儲子串指針
int count = 0;
printf("Splitting string \"%s\" into tokens:\n", str);
pch = strtok(str, " ,.-");
while (pch != NULL && count < 20) {
tokens[count++] = pch; // 保存子串指針
printf("%s\n", pch);
pch = strtok(NULL, " ,.-");
}
printf("\nTokens stored in pointer array:\n");
for (int i = 0; i < count; i++) {
printf("tokens[%d] = %s\n", i, tokens[i]);
}
printf("at the end: %s\n", str); // 原字符串已被修改
return 0;
}
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
Tokens stored in pointer array:
tokens[0] = This
tokens[1] = a
tokens[2] = sample
tokens[3] = string
at the end: - This, a sample string.
推薦使用C++標準庫,更安全且功能豐富:
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& s, const std::string& delim) {
std::vector<std::string> tokens;
size_t start = 0, end = 0;
while ((end = s.find(delim, start)) != std::string::npos) {
tokens.push_back(s.substr(start, end - start));
start = end + delim.length();
}
tokens.push_back(s.substr(start));
return tokens;
}
strtok是C語言風格的經典做法,理解指針操作有助於掌握底層機制std::string和STL容器,避免內存管理錯誤strtok非線程安全,多線程環境下應使用strtok_r或C++標準庫