📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Counting the occurrence of a character in a string is a common programming task. It allows us to determine the frequency of a specific character within a given string. In this blog post, we will explore a Kotlin program that efficiently counts the occurrence of a character in a string. We will walk through the program step by step, explaining the logic behind it.
Kotlin Program: Counting the Occurrence of a Character in a String
fun countOccurrences(str: String, ch: Char): Int {
var count = 0
for (element in str) {
if (element == ch) {
count++
}
}
return count
}
fun main() {
val inputString = "Hello, World!"
val character = 'o'
val occurrenceCount = countOccurrences(inputString, character)
val character1 = 'l'
val occurrenceCount1 = countOccurrences(inputString, character1)
println("The character '$character' occurs $occurrenceCount times in the string.")
println("The character '$character1' occurs $occurrenceCount1 times in the string.")
}
Output:
The character 'o' occurs 2 times in the string.
The character 'l' occurs 3 times in the string.
The countOccurrences() function takes a string str and a character ch as input and returns the count of occurrences of ch in str.
We initialize a variable count to 0 to keep track of the occurrence count.
We iterate through each character element in the str string using a for loop.
Inside the loop, we compare each element with the given character ch. If they are equal, we increment the count by 1.
After iterating through all the characters in the string, we return the final count value.
In the main() function, we create a sample input string (val inputString = "Hello, World!") and specify the character we want to count (val character = 'o').
We call the countOccurrences() function with the input string and character, and the returned occurrence count is stored in the occurrenceCount variable.
Finally, we print the result to the console using println().
Conclusion
Feel free to explore and modify the code to suit your specific needs. The concept of counting occurrences is essential in various programming scenarios, such as text processing, data analysis, and algorithmic challenges. Happy coding!
Comments
Post a Comment
Leave Comment