我有找到句子中最长和最短单词的代码。但如何找到常见的字母 这两个词(要添加到程序中的内容是什么?)?在C中
#include<stdio.h>
#include<string.h>
int main() {
long int i=0,j=0,k=0,a,minIndex=0,maxIndex=0,max=0,min=0;
char str1[100]={0},substr[100][100]={0};
printf("Enter a sentence\n");
gets(str1);
while(str1[k]!='\0') {
j=0;
while(str1[k]!=' '&&str1[k]!='\0') {
substr[i][j]=str1[k];
k++; j++;
}
substr[i][j]='\0';
i++;
if(str1[k]!='\0') {
k++;
}
}
long int len=i;
max=strlen(substr[0]);
min=strlen(substr[0]);
for(i=0;i<len;i++) {
a=strlen(substr[i]);
if(a>max) {
max=a; maxIndex=i;
}
if(a<min) {
min=a; minIndex=i;
}
}
printf("Largest Word is %s \nSmallest word is %s\n",substr[maxIndex],substr[minIndex]);
}
最佳答案
删除代码末尾的 printf
并在关闭 main()
方法之前将以下行添加到代码中。
int common[26] = {0};
for(i = 0; i < strlen(substr[minIndex]); i++)
{
for(j = 0; j < strlen(substr[maxIndex]); j++)
{
if(tolower(substr[maxIndex][j]) == tolower(substr[minIndex][i]))
{
common[tolower(substr[minIndex][i]) - 'a'] = 1;
}
}
}
for(i = 0; i < 26; i++)
{
if(common[i] == 1)
{
printf("%c\n", (i + 'a'));
}
}
它的作用是,它将最长单词中的每个字母与最短单词中的每个字母进行比较,对于每个匹配,它将 common
字母表数组中的相应索引标记为 1
。遍历完所有字母后,我们只需迭代 common
数组并打印标记的字母即可。
完整的工作代码如下:
#include<stdio.h>
#include<string.h>
int main() {
long int i=0,j=0,k=0,a,minIndex=0,maxIndex=0,max=0,min=0;
char str1[100]={0},substr[100][100]={0};
printf("Enter a sentence\n");
gets(str1);
while(str1[k]!='\0') {
j=0;
while(str1[k]!=' '&&str1[k]!='\0') {
substr[i][j]=str1[k];
k++; j++;
}
substr[i][j]='\0';
i++;
if(str1[k]!='\0') {
k++;
}
}
long int len=i;
max=strlen(substr[0]);
min=strlen(substr[0]);
for(i=0;i<len;i++) {
a=strlen(substr[i]);
if(a>max) {
max=a; maxIndex=i;
}
if(a<min) {
min=a; minIndex=i;
}
}
printf("The longest word is: %s \nThe shortest word is: %s\n",substr[maxIndex],substr[minIndex]);
int common[26] = {0};
for(i = 0; i < strlen(substr[minIndex]); i++)
{
for(j = 0; j < strlen(substr[maxIndex]); j++)
{
if(tolower(substr[maxIndex][j]) == tolower(substr[minIndex][i]))
{
common[tolower(substr[minIndex][i]) - 'a'] = 1;
}
}
}
printf("Common letters between the longest word and the shortest word are: ");
for(i = 0; i < 26; i++)
{
if(common[i] == 1)
{
printf("%c, ", (i + 'a'));
}
}
printf("\b\b ");
}
输入
This is Isomorphic
输出
The longest word is: Isomorphic
The shortest word is: is
Common letters between the longest word and the shortest word are: i, s
关于c - 如何找到句子中最短和最长单词之间的共同字母,C语言中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60207744/