How to reverse the order of words in a C language strin…
To reverse the order of the words in a C language string, you can follow these steps:
- invert the order of words
- splitting a string into smaller tokens
- Calculate the number of words.
- Output each word in reverse order using a loop.
Here is an example code:
#include <stdio.h>
#include <string.h>
void reverse_words(char str[]) {
char *token;
char *words[100]; // 假设最多有100个单词
int count = 0;
// 使用strtok函数分割字符串并将每个单词存储在数组中
token = strtok(str, " ");
while (token != NULL) {
words[count] = token;
count++;
token = strtok(NULL, " ");
}
// 倒序输出每个单词
for (int i = count - 1; i >= 0; i--) {
printf("%s ", words[i]);
}
}
int main() {
char str[] = "Hello World, I am a student.";
reverse_words(str);
return 0;
}
The output result is:
student. a am I World, Hello