c语言中查找最长单词并输出它和它的长度
时间: 2024-06-13 20:08:59 浏览: 448
以下是C语言中查找最长单词并输出它和它的长度的代码示例:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], word[100]; int i, j = 0, len, max = 0;
printf("请输入一个字符串:");
gets(str);
len = strlen(str);
for (i = 0; i <= len; i++)
{
if (str[i] == ' ' || str[i] == '\0')
{
word[j] = '\0';
if (strlen(word) > max)
{
max = strlen(word);
printf("最长的单词:%s,长度:%d\n", word, max);
}
j = 0;
}
else
{
word[j] = str[i];
j++;
}
}
return 0;
}
```
相关问题
c语言查找最长的单词
在C语言中,查找字符串中最长的单词通常涉及到几个步骤。首先,你需要遍历输入的字符串,然后分割出每个单词。这可以使用`strtok()`函数配合指针完成,它会按照空格分隔字符串。接着,你需要维护两个变量:一个存储当前找到的最长单词的长度,另一个存储最长单词本身。
以下是一个简单的示例代码片段:
```c
#include <stdio.h>
#include <string.h>
#define MAX_WORD_LENGTH 100
void find_longest_word(char *input) {
char word[MAX_WORD_LENGTH];
char *token = strtok(input, " ");
int longest_length = 0;
char longest_word[MAX_WORD_LENGTH];
while (token != NULL) {
int current_length = strlen(token);
if (current_length > longest_length) {
strcpy(longest_word, token);
longest_length = current_length;
}
token = strtok(NULL, " ");
}
printf("最长的单词是 \"%s\",长度为 %d\n", longest_word, longest_length);
}
int main() {
char input[] = "This is a test sentence with some long words.";
find_longest_word(input);
return 0;
}
```
在这个例子中,`find_longest_word` 函数会找出并打印输入字符串中最长的单词及其长度。注意,这个代码假设单词是由空格分隔开的,并且不会处理标点符号或其他非字母字符。
c语言 统计字符串内单词 输出单词个数 最长单词 最大单词
在C语言中统计字符串内的单词、输出单词个数、最长单词和最大单词长度通常涉及到遍历字符串、分割以及存储和比较数据的过程。这里是一个基本的步骤:
1. **统计单词个数**:
- 使用`strtok`函数将字符串按空格分割成单词数组。
- 遍历数组,每遇到非空指针就增加词数。
```c
#include <stdio.h>
#include <string.h>
int count_words(char *str) {
int word_count = 0;
char *token = strtok(str, " ");
while (token != NULL) {
word_count++;
token = strtok(NULL, " ");
}
return word_count;
}
```
2. **找出最长单词**:
- 你可以使用动态内存分配存储每个单词,并记录当前最长的单词及其长度。
```c
char* longest_word(char *str) {
int max_len = 0;
char* longest_word_ptr = "";
// ...遍历字符串,更新max_len和longest_word_ptr...
return longest_word_ptr; // 返回最长单词
}
// 示例:
int main() {
char str[] = "This is a sample sentence.";
int word_count = count_words(str);
char* longest = longest_word(str);
printf("Words: %d, Longest Word: %s\n", word_count, longest);
free(longest); // 不要忘记释放内存
return 0;
}
```
3. **查找最大单词长度**:
- 直接遍历,同时记录最大长度即可。
```c
int max_word_length(char *str) {
int len = strlen(str);
int max_length = 0;
for (int i = 0; i < len; i++) {
if (str[i] == ' ') {
if (i+1 < len && str[i+1] != '\0') {
max_length = (max_length > strlen(&str[i + 1])) ? max_length : strlen(&str[i + 1]);
} else {
max_length = (max_length > i) ? max_length : i;
}
}
}
return max_length;
}
```
阅读全文
相关推荐
















