#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
char s[] = "my name is lmm";
char *p;
const char *delim = " ";
p = strtok(s, delim);
while(p) {
cout << p << endl;
p = strtok(NULL, delim);
}
return 0;
gdb调试
18 char s[] = "my name is lmm";
Missing separate debuginfos, use: debuginfo-install glibc-2.17-222.el7.x86_64 libgcc-4.8.5-16.el7.x86_64 libstdc++-4.8.5-16.el7.x86_64
(gdb) n
20 const char *delim = " ";
(gdb) p s
$1 = "my name is lmm"
(gdb) n
21 p = strtok(s, delim);
(gdb) n
22 while(p) {
(gdb) p p
$2 = 0x7fffffffdd10 "my" p的指向是一个分离的字符串
(gdb)
p = strtok(NULL, delim);
参数==NULL 仍然使用上次的#位置(存在静态变量中)开始继续找,直到找到下一个分隔符#。
function
<cstring>
strtok
char * strtok ( char * str, const char * delimiters );
Split string into tokens
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning.
To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token. The scan also stops if the terminating null character is found.
This end of the token is automatically replaced by a null-character, and the beginning of the token is returned by the function.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
The point where the last token was found is kept internally by the function to be used on the next call (particular library implementations are not required to avoid data races).
Parameters
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters.
These can be different from one call to another.
Return Value
If a token is found, a pointer to the beginning of the token.
Otherwise, a null pointer.
A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned.
Example
| |
Output:
|