如何计算字符串中每个字母c(忽略大小写)的出现次数?因此它会打印出letter: # number of occurences
,我有代码来计算一个字母的出现次数,但是如何计算字符串中每个字母的出现次数?
{
char
int count = 0;
int i;
//int length = strlen(string);
for (i = 0; i < 20; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
输出:
a : 1
b : 0
c : 2
etc...
答案 0 :(得分:8)
假设您有一个char
为8位的系统,并且您尝试计算的所有字符都使用非负数进行编码。在这种情况下,您可以写:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
请注意,这将计算字符串中的所有字符。如果你100%绝对肯定你的字符串里面只有字母(没有数字,没有空格,没有标点符号),那么1.要求“不区分大小写”开始有意义,2。你可以减少条目数到英文字母中的字符数(即26),你可以这样写:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
答案 1 :(得分:1)
像这样:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
此代码假定字符串以空值终止,并且它仅包含字符a
到z
或A
到Z
,包括在内。
要了解其工作原理,请注意转化后tolower
每个字母的代码都在a
和z
之间,并且代码是连续的。因此,tolower(*p) - 'a'
评估为0
到25
之间的数字,包括字母表中字母的序号。
此代码将++
和*p
结合起来缩短程序。
答案 2 :(得分:1)
一个简单的可能性是制作一个26个整数的数组,每个都是一个字母a-z的计数:
int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc
然后遍历字符串并递增每个字母的计数:
for(int i = 0; i<strlen(mystring); i++) //for the whole length of the string
if(isalpha(mystring[i]))
alphacount[tolower(mystring[i])-'a']++; //make the letter lower case (if it's not)
//then use it as an offset into the array
//and increment
这是一个适用于A-Z,a-z的简单想法。如果你想用大写字母分开,你只需要改变计数52并减去正确的ASCII偏移量
答案 3 :(得分:1)
接受答复后
满足这些规范的方法:( IMO,其他答案不符合所有要求)
当char
具有宽范围时,它是实用/高效的。示例:CHAR_BIT
为16
或32
,因此不使用bool Used[1 << CHAR_BIT];
适用于非常长字符串(使用size_t
而不是int
)。
不依赖于ASCII。 (Use Upper[]
)
char
&lt; is...()
时的定义行为0. EOF
函数是为unsigned char
和static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
void LetterOccurrences(size_t *Count, const char *s) {
memset(Count, 0, sizeof *Count * 26);
while (*s) {
unsigned char ch = *s;
if (isalpha(ch)) {
const char *caseset = Upper;
char *p = strchr(caseset, ch);
if (p == NULL) {
caseset = Lower;
p = strchr(caseset, ch);
}
if (p != NULL) {
Count[p - caseset]++;
}
}
}
}
// sample usage
char *s = foo();
size_t Count[26];
LetterOccurrences(Count, s);
for (int i=0; i<26; i++)
printf("%c : %zu\n", Upper[i], Count[i]);
}
{{1}}
答案 4 :(得分:1)
#include <stdio.h>
#include <string.h>
void main()
{
printf("PLEASE ENTER A STRING\n");
printf("GIVE ONLY ONE SPACE BETWEEN WORDS\n");
printf("PRESS ENETR WHEN FINISHED\n");
char str[100];
int arr[26]={0};
char ch;
int i;
gets(str);
int n=strlen(str);
for(i=0;i<n;i++)
{
ch=tolower(str[i]);
if(ch>=97 && ch<=122)
{
arr[ch-97]++;
}
}
for(i=97;i<=122;i++)
printf("%c OCCURS %d NUMBER OF TIMES\n",i,arr[i-97]);
return 0;
}
答案 5 :(得分:0)
您可以使用以下代码。
main()
{
int i = 0,j=0,count[26]={0};
char ch = 97;
char string[100]="Hello how are you buddy ?";
for (i = 0; i < 100; i++)
{
for(j=0;j<26;j++)
{
if (tolower(string[i]) == (ch+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",97+j,count[j]);
}
}
希望这有帮助。
答案 6 :(得分:0)
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
答案 7 :(得分:0)
for (int i=0;i<word.length();i++){
int counter=0;
for (int j=0;j<word.length();j++){
if(word.charAt(i)==word.charAt(j))
counter++;
}// inner for
JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
}// outer for
答案 8 :(得分:0)
以下是带有用户定义函数的C代码:
/* C Program to count the frequency of characters in a given String */
#include <stdio.h>
#include <string.h>
const char letters[] = "abcdefghijklmnopqrstuvwxzy";
void find_frequency(const char *string, int *count);
int main() {
char string[100];
int count[26] = { 0 };
int i;
printf("Input a string: ");
if (!fgets(string, sizeof string, stdin))
return 1;
find_frequency(string, count);
printf("Character Counts\n");
for (i = 0; i < 26; i++) {
printf("%c\t%d\n", letters[i], count[i]);
}
return 0;
}
void find_frequency(const char *string, int *count) {
int i;
for (i = 0; string[i] != '\0'; i++) {
p = strchr(letters, string[i]);
if (p != NULL) {
count[p - letters]++;
}
}
}
答案 9 :(得分:0)
#include<stdio.h>
void frequency_counter(char* str)
{
int count[256] = {0}; //partial initialization
int i;
for(i=0;str[i];i++)
count[str[i]]++;
for(i=0;str[i];i++) {
if(count[str[i]]) {
printf("%c %d \n",str[i],count[str[i]]);
count[str[i]]=0;
}
}
}
void main()
{
char str[] = "The quick brown fox jumped over the lazy dog.";
frequency_counter(str);
}
答案 10 :(得分:0)
已经检查了许多答案是否与静态数组有关,如果假设我在字符串中具有特殊字符并且想要一个具有动态概念的解决方案该怎么办?可能还有许多其他可能的解决方案,这就是其中之一。
这是链接列表的解决方案。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node {
char data;
int counter;
struct Node* next;
};
void printLinkList(struct Node* head)
{
while (head != NULL) {
printf("\n%c occur %d", head->data, head->counter);
head = head->next;
}
}
int main(void) {
char *str = "!count all the occurances of character in string!";
int i = 0;
char tempChar;
struct Node* head = NULL;
struct Node* node = NULL;
struct Node* first = NULL;
for(i = 0; i < strlen(str); i++)
{
tempChar = str[i];
head = first;
if(head == NULL)
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
if(first == NULL)
{
first = node;
}
}
else
{
while (head->next != NULL) {
if(head->data == tempChar)
{
head->counter = head->counter + 1;
break;
}
head = head->next;
}
if(head->next == NULL)
{
if(head->data == tempChar)
{
head->counter = head->counter + 1;
}
else
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
head->next = node;
}
}
}
}
printLinkList(first);
return 0;
}
答案 11 :(得分:-1)
int charset[256] = {0};
int charcount[256] = {0};
for (i = 0; i < 20; i++)
{
for(int c = 0; c < 256; c++)
{
if(string[i] == charset[c])
{
charcount[c]++;
}
}
}
charcount将存储字符串中任何字符的出现。
答案 12 :(得分:-1)
//这是JavaScript代码。
function countWordOccurences()
{
// You can use array of words or a sentence split with space.
var sentence = "The quick brown fox jumped over the lazy dog.";
//var sentenceArray = ['asdf', 'asdf', 'sfd', 'qwr', 'qwr'];
var sentenceArray = sentence.split(' ', 1000);
var output;
var temp;
for(var i = 0; i < sentenceArray.length; i++) {
var k = 1;
for(var j = i + 1; j < sentenceArray.length; j++) {
if(sentenceArray[i] == sentenceArray[j])
k = k + 1;
}
if(k > 1) {
i = i + 1;
output = output + ',' + k + ',' + k;
}
else
output = output + ',' + k;
}
alert(sentenceArray + '\n' + output.slice(10).split(',', 500));
}
You can see it live --> http://jsfiddle.net/rammipr/ahq8nxpf/
答案 13 :(得分:-1)
// c代码,用于计算字符串中每个字符的出现次数。
void main()
{
int i,j; int c[26],count=0; char a[]="shahid";
clrscr();
for(i=0;i<26;i++)
{
count=0;
for(j=0;j<strlen(a);j++)
{
if(a[j]==97+i)
{
count++;
}
}
c[i]=count;
}
for(i=0;i<26;i++)
{
j=97+i;
if(c[i]!=0) { printf("%c of %d times\n",j,c[i]);
}
}
getch();
}
答案 14 :(得分:-1)
protected void btnSave_Click(object sender, EventArgs e)
{
var FullName = "stackoverflow"
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
// Label1.Text=item.Value + " " + item.Key + "<br />";
spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
}
}