字符数 [英] Number of characters
问题描述
hi
我必须写一个程序来获取一个字符串并告诉它的字符数。
就像我的字符串是aaabb,程序的输出应该是:
a:3
b:2
idk怎么写:(< br $> b $ b
我的尝试:
hi
I have to write a program that gets a string and tells the number of its characters .
like my string is "aaabb" , the program's output should be :
a : 3
b : 2
idk how to write it :(
What I have tried:
#include<stdio.h>
int main()
{
char a[50],ch;
int i,j,n=0;
printf("enter your string :\t");
gets(a);
for(i=0;a[i]!='\0';i++){
for(j=0;a[j]!='\0';j++){
if(a[i]==a[j])
n++;
}
printf(" %c : %d \n",j,n);
}
}
推荐答案
很少有修改可以完成这项工作。
Few modifications should do the job.
#include<stdio.h>
int main()
{
char a[50],ch;
int i,j,n=0;
printf("enter your string :\t");
gets(a);
for(i=0;a[i]!='\0';i++){
n=0; //reset the count for next character in queue
for(j=0;a[j]!='\0';j++){
if(a[i]==a[j])
n++;
}
printf(" %c : %d \n",i,n);//show i instead of j
}
}
当你为字符串中的每个字符进行迭代而不检查重复时,你仍然会看到重复的行。为了解决这个问题,您可以应用逻辑来创建一个具有唯一字符的字符串,并且您需要将其用于外部循环(i)。
查看以下链接以获取有关的帮助那个 -
C程序删除字符串中的所有重复字符 - Codeforwin [ ^ ]
删除给定字符串中的所有重复项 - GeeksforGeeks [ ^ ]
跳,它有帮助:)
You'll still be seeing duplicate lines as you are iterating for each characters in the string without checking for duplicates. To overcome this, you can apply logic to have a string with unique characters and that you need to use for outer loop (i).
Check following links for help regarding that-
C program to remove all repeated characters in a string - Codeforwin[^]
Remove all duplicates from a given string - GeeksforGeeks[^]
Hop, it helps :)
这篇关于字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!