Swift Program to count a specified character inside the string


In Swift, to count how many times a specified character occurs in the given string we create a function. It will increase the value of the counter by one whenever the specified character appears in the given string and then return the final count at the end of the given string.

Input

String = “Today is cloudy day”
Character = “y”

Output

3

Where, character “y” appears three times in the given string so the output of the input is 3.

Algorithm

  • Step 1 − Create a function that returns the specified character's total occurrence.

  • Step 2 − Inside the function, we will create a counter to count the occurrence of the specified character.

  • Step 3 − Run a for-in loop to iterate over the characters of the input string and check whether the current character is equal to the specified character or not.

  • Step 4 − If the current character is equal to the specified character increase the value of the counter by one. This process will continue till the last character of the string.

  • Step 5 − Return the final count.

  • Step 6 − Create a string.

  • Step 7 − Create a variable to store the character.

  • Step 8 − Call the function and pass the string and the character into it as an argument.

  • Step 9 − Print the output.

Example

In the following Swift program, we will count a specified character inside the string. So for that, we will create a function that counts the specified character's total occurrence in the given string. Then use a for-in loop to iterate through each character of the given string, and if the current character is equal to the specified character, then it will increase the value of count by one. This process continues till the last character of the string and returns the final count. After that, we will call this function, pass the specified character and string into it as an argument, and display the final result.

import Foundation
import Glibc

func countAppearance(char: Character, str: String) -> Int {

   var counter = 0
   
   // Counting the occurrence of the 
   // specified character
   for mChar in str {
      if mChar == char {
         counter += 1
      }
   }
   return counter
}

let mStr = "Learn Swift Language"
let xchar : Character = "a"

let result = countAppearance(char: xchar, str: mStr)
print("Character 'a' occur \(result) times in '\(mStr)' string")

Output

Character 'a' occur 3 times in 'Learn Swift Language' string

Conclusion

So this is how we can count a specified character inside the string. The above-discussed method returns only the count of a single character. If you want to find the count of multiple characters, then you need to create a dictionary to store the characters and their count.

Updated on: 09-May-2023

815 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements