租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

C语言strstr和strtok函数如何使用,c语言中strstr

发布时间:2023-08-03 08:29:16

C语言strstr和strtok函数如何使用

C语言的strstr函数用于在一个字符串中查找另外一个字符串的第一次出现位置。它的使用方法以下:
```c
#include
#include
int main() {
char str[] = "This is a test string";
char *result;
result = strstr(str, "test");
if(result == NULL) {
printf("Substring not found ");
}
else {
printf("Substring found at index %ld ", result - str);
}
return 0;
}
```
输出结果为:Substring found at index 10,表示在字符串str中找到了子字符串"test",其起始位置为索引10。
C语言的strtok函数用于将一个字符串分割成一系列子字符串。它的使用方法以下:
```c
#include
#include
int main() {
char str[] = "This is a test string";
char *token;
token = strtok(str, " ");
while(token != NULL) {
printf("%s ", token);
token = strtok(NULL, " ");
}
return 0;
}
```
输出结果为:
This
is
a
test
string
这个例子将字符串str依照空格进行分割,并逐一打印出每一个子字符串。