Home  >  Article  >  Backend Development  >  C program: Find the minimum number of occurrences of a character in a string

C program: Find the minimum number of occurrences of a character in a string

WBOY
WBOYforward
2023-08-27 19:25:04945browse

C program: Find the minimum number of occurrences of a character in a string

字符数组被称为字符串。

声明

以下是声明数组的声明方式 −

char stringname [size];

例如 − char string[50]; 长度为50个字符的字符串

初始化

  • 使用单个字符常量 −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 使用字符串常量 −
char string[10] = "Hello":;

访问 − 有一个控制字符串 "%s" 用于访问字符串,直到遇到 ‘\0’。

查找最小出现次数

查找给定字符串中字符的最小出现次数的逻辑如下 −

for(i=0; i<CHARS; i++){
   if(frequency[i]!=0){
      if(frequency[minimum] == 0 || frequency[i]< fequency[minimum]) minimum = i;
}

程序

以下是查找字符串中出现次数最少的字符的 C 程序。

#include<stdio.h>
#define SIZE 100 // Maximum string size
#define CHARS 255 // Maximum characters allowed
int main(){
   char string[SIZE];
   int frequency[CHARS];
   int i = 0, minimum;
   int value;
   printf("Enter the string:</p><p> ");
   gets(string);
   for(i=0; i<CHARS; i++){
      frequency[i] = 0; // initialize freq of all char to zero
   }
   i=0;
   while(string[i] != &#39;\0&#39;){ // finding freq of each char
      value = (int)string[i];
      frequency[value] += 1;
      i++;
   }
   minimum = 0;
   for(i=0; i<CHARS; i++){// finding min freq
      if(frequency[i]!=0){
         if(frequency[minimum] == 0 || frequency[i]<fequency[minimum])
            minimum = i;
   }
   printf("Minimum occurrence character is &#39;%c&#39; = %d times.", minimum,    frequency[minimum]);
   return 0;
}

输出

当执行上述程序时,会产生以下结果 -

Enter the string:
tutorialspoint
Minimum occurrence character is &#39;a&#39; = 1 times.

The above is the detailed content of C program: Find the minimum number of occurrences of a character in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete