Home > Backend Development > C++ > 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
Release: 2023-08-27 19:25:04
forward
976 people have browsed it

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

字符数组被称为字符串。

声明

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

char stringname [size];
Copy after login

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

初始化

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

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

查找最小出现次数

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

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

程序

以下是查找字符串中出现次数最少的字符的 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;
}
Copy after login

输出

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

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template