输入一句英文句子不包括标点符号,但句子前可能包含空格,可能不大写,输出单词个数,用c语言写
时间: 2023-05-30 09:04:31 浏览: 85
#include <stdio.h>
#include <ctype.h>
int main() {
char sentence[1000]; // 假设句子最长为1000个字符
int count = 0; // 计数器初始化为0
printf("请输入句子:");
gets(sentence); // 输入句子,包括空格
// 判断句子开头是否是空格,是则去掉
if (isspace(sentence[0])) {
for (int i = 0; sentence[i]; i++) {
sentence[i] = sentence[i + 1];
}
}
// 统计单词数
for (int i = 0; sentence[i]; i++) {
if (isspace(sentence[i])) {
count++;
}
}
count++; // 最后一个单词后没有空格,需要加1
printf("单词个数为:%d\n", count);
return 0;
}
相关问题
C语言给定一个字符串把其中各个单词的顺序颠倒,注意保持句首字母大写,标点符号不动。
可以使用以下步骤实现:
1. 定义一个函数,接受一个字符串参数,返回一个字符串结果。
2. 定义一个数组,存储每个单词的起始位置和长度。
3. 遍历字符串,找到每个单词的起始位置和长度,并将其存储到数组中。
4. 遍历数组,将每个单词反转。
5. 遍历数组,将每个单词的首字母大写。
6. 遍历数组,将每个单词连接起来,中间加上空格。
下面是实现该函数的代码:
```c
#include <ctype.h>
#include <string.h>
char* reverseWords(char* s) {
int len = strlen(s);
int words[100][2];
int count = 0;
int i = 0;
while (i < len) {
while (i < len && isspace(s[i])) i++;
if (i == len) break;
words[count][0] = i;
while (i < len && !isspace(s[i])) i++;
words[count][1] = i - words[count][0];
count++;
}
for (int i = 0; i < count; i++) {
int start = words[i][0];
int end = words[i][0] + words[i][1] - 1;
while (start < end) {
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
for (int i = 0; i < count; i++) {
int idx = words[i][0];
s[idx] = toupper(s[idx]);
}
char* result = malloc(len + 1);
memset(result, 0, len + 1);
for (int i = 0; i < count; i++) {
int start = words[i][0];
strncat(result, s + start, words[i][1]);
if (i < count - 1) strcat(result, " ");
}
return result;
}
```
注意,该函数返回的字符串需要手动释放。可以这样调用:
```c
char* s = "Hello, world!";
char* result = reverseWords(s);
printf("%s\n", result);
free(result);
```
C语言,给定一个字符串把其中各个单词的顺序颠倒,注意保持句首字母大写,标点符号不动。
可以使用以下步骤实现:
1. 定义一个函数,接受一个字符串参数,返回一个字符串结果。
2. 定义两个指针,分别指向字符串的开头和结尾。
3. 从结尾向开头遍历字符串,找到每个单词的结尾位置。
4. 再从每个单词的结尾位置向开头遍历,将每个单词反转。
5. 遍历字符串,将每个单词的首字母大写。
6. 遍历字符串,将每个单词连接起来,中间加上空格。
下面是实现该函数的代码:
```c
#include <ctype.h>
#include <string.h>
char* reverseWords(char* s) {
int len = strlen(s);
char* start = s;
char* end = s + len - 1;
while (isspace(*end)) end--;
char* word_end = end;
while (word_end >= start) {
if (isspace(*word_end)) {
int word_len = end - word_end;
char* word_start = word_end + 1;
for (char* p = word_start; p < end; p++) {
char tmp = *p;
*p = *word_end;
*word_end = tmp;
word_end--;
}
end = word_end;
word_end -= word_len + 1;
} else {
word_end--;
}
}
for (char* p = s; p <= end; p++) {
if (p == s || isspace(*(p - 1))) {
*p = toupper(*p);
}
}
char* result = malloc(len + 1);
memset(result, 0, len + 1);
char* p = s;
while (p <= end) {
if (!isspace(*p)) {
strncat(result, p, 1);
} else if (p > s && !isspace(*(p - 1))) {
strcat(result, " ");
}
p++;
}
return result;
}
```
注意,该函数返回的字符串需要手动释放。可以这样调用:
```c
char* s = "Hello, world!";
char* result = reverseWords(s);
printf("%s\n", result);
free(result);
```