2024年6月14日发(作者:)

c 字符串截取空格后的字符串

在C语言中,可以使用以下方法截取字符串中的空格后的字符串:

1. 使用strtok函数:

```c

#include

#include

int main() {

char str[] = " Hello World ";

char *token;

// 使用空格作为分隔符

token = strtok(str, " ");

// 循环获取每个子字符串

while (token != NULL) {

// 输出每个子字符串

printf("%sn", token);

// 继续获取下一个子字符串

token = strtok(NULL, " ");

}

return 0;

}

```

输出结果:

```

Hello

World

```

2. 使用循环遍历字符串的每个字符:

```c

#include

#include

int main() {

char str[] = " Hello World ";

int start = 0;

int end = strlen(str) - 1;

// 找到第一个非空格字符的位置

while (str[start] == ' ') {

start++;

}

// 找到最后一个非空格字符的位置

while (str[end] == ' ') {

end--;

}

// 截取非空格字符之间的字符串

for (int i = start; i <= end; i++) {

printf("%c", str[i]);

}

return 0;

}

```

输出结果:

```