C Program To Count Repeated Character In A String

 admin
C Program To Count Repeated Character In A String Rating: 8,2/10 1693 votes

Continue reading C program to count frequency of each character in a string → Learn C programming, Data Structures tutorials, exercises, examples, programs, hacks, tips and tricks online. A blog for beginners to advance their skills in programming. C program to find the frequency of characters in a string: This program counts the frequency of characters in a string, i.e., which character is present how many times in the string. For example, in the string 'code' each of the characters 'c,' 'd,' 'e,' and 'o' has occurred one time.

Active4 months ago
$begingroup$

I was trying to do a very common interview problem 'Finding the max repeated word in a string ' and could not find much resources in net for c/c++ implementation. So I coded it myself here. I have tried to do most of the coding from scratch for better understanding. Could you review my code and provide comments on my algorithm. Some people have suggested using hashtables for storing the count, but am not using hashtables here.

David Harkness
8,5381 gold badge21 silver badges43 bronze badges
user2745
$endgroup$

3 Answers

$begingroup$

Here's a long list of feedback. Sorry for the blunt tone, but I'm trying to be brief:

  1. parsestr mutates a global variable but returns a value that's relevant to that variable (the count). That's inconsistent. Either have it return both the count and the array (or make things easier on yourself and use a vector that knows its size), or make the count global too.

  2. You don't handle punctuation characters. Is that a requirement? Should
    'a(b)' be one word? Should 'a. a' be two unique words?

  3. Do you need to split on characters other than space? What about t or n? Other Unicode whitespace characters?

  4. Your while(i < maxlength) loop could more simply be a for loop.

  5. Building up the word by incrementally contatenating characters onto a string is slow. It will periodically require dynamic allocation. A more efficient solution would be to remember the start index of the word. When you reach the end, create a string from the substring (start, end) in one step.

    Going further from there, there's no reason to even store those wordsseparately since that start, end pair is enough to reconstruct it as needed.

  6. Your program will mysteriously crash if you pass a sentence with more thanten words. :( Since you're using dynamic allocation everywhere else (stringdoes that under the hood) there's no reason to use a fixed array for words.At the very least, you should have a constant for that size and check thatyou don't overflow the array.

  7. index isn't a helpful variable name. Call it wordIndex.

  8. Likewise, wordcnt would be better as wordCount.

  9. maxrepeatedWord is a mixture of camelCase and all lowercase. Be consistent(and camelCase is generally better since it makes it easier for the readerto split it into words).

  10. wordcntArr would be better as wordCounts. The fact that it's an array isself-evident.

  11. i <= count should be just <. Arrays are zero-based, so wordcntArr[count] is past the last valid element.

  12. index ->indexOfMax.

  13. You're passing count into countwords even though that count is relevant to a global variable that it accesses directly. Why not just make the count global too?

  14. The else {} accomplishes nothing. Remove it.

  15. If you declare wordcnt inside the for(int i.. loop, you won't have toreinitialize it each iteration.

  16. int wordcntArr[10] again duplicates the magical literal 10. Use a constant or, better, a dynamically-sized container.

  17. You're redundantly recounting each word every time it occurs. With'I am am am good good', you'll get a count array like 1 3 3 3 2 2. If you had a collection of unique words instead, your $O(n^2)$ complexitywould go down to $O(mn)$ where $m$ is the number of unique words.

    A hash table would be a good way to create the set of unique words.

  18. Your test string assumes repeated words will be contiguous (as opposed to,say 'I am good am good am.'). Is that intentional? Handbook of textile auxiliaries and chemicals. Desirable?

At a high level, your algorithm is also not optimal. You've got $O(n^2)$ performance, ignoring the dynamic allocation as you incrementally build up those strings. With that, it gets worse.

I believe the canonical solution to this is (roughly):

That gives you $O(n)$: you only walk the entire string once.

esote
3,0611 gold badge13 silver badges41 bronze badges
munificentmunificent
$endgroup$$begingroup$

Some general comments first:

  1. Comment, comment, comment. Although it seems pretty clear now, it doesn't hurt to make it really clear for the guy who has to maintain it when you've moved on.

  2. You might want to have separate functions for doing the counting of the words and for displaying the counts of the words.

C++ Comments:

  1. You are using C++, so you might want to put this in a Class.

  2. The Standard Library is your friend. In particular, you might want to see if std::map<..> could make your life a little easier when counting words.

  3. The use of string word[10] makes an assumption of how many different words there will be. It would be better to allow an arbitrary number of different words by using something like a std::vector. Alternatively, a different approach could be used (see #4).

  4. string.find(.) and string.sub_string(.) might prove helpful.

Toby Speight
31.4k7 gold badges45 silver badges135 bronze badges
jwernernyjwernerny
$endgroup$$begingroup$

There are two aspects of the problem statement that are unclear (that's quite probably intentional, given that this is an interview question).

  1. What constitutes a 'word' here? Splitting the string on spaces is one possibility, but means that a word bounded by punctuation will be considered different to the same word standing alone. We can't completely ignore punctuation, though - cant and can't are completely different words, for example.

  2. What if there isn't a single most frequent word? There might be a draw, or there might be no words in the input at all. What should we return in those cases? (My recommendation: always return a container (e.g. std::vector) of results, and let the caller choose what to do if it's length is not 1.)

If you're not in a position to obtain answers to these questions, it's important to include comments indicating the assumptions you've made (i.e. your guesses at the answers).

Toby SpeightToby Speight
31.4k7 gold badges45 silver badges135 bronze badges
$endgroup$
Active1 year, 8 months ago

This question already has an answer here:

  • How would you count occurrences of a string (actually a char) within a string? 30 answers

I simply have a string that looks something like this:

'7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false'

All I want to do is to count how many times the string 'true' appears in that string. I'm feeling like the answer is something like String.CountAllTheTimesThisStringAppearsInThatString() but for some reason I just can't figure it out. Help?

Milad Rashidi
8494 gold badges12 silver badges29 bronze badges
onekidneyonekidney
2,9866 gold badges38 silver badges59 bronze badges

marked as duplicate by nawfal, PaRiMaL RaJ, luke, Fox32, jcwengerApr 25 '13 at 15:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7 Answers

Chris Benard
2,4591 gold badge20 silver badges33 bronze badges
µBioµBio
9,2946 gold badges32 silver badges54 bronze badges

Probably not the most efficient, but think it's a neat way to do it.

rjdevereuxrjdevereux
1,0432 gold badges13 silver badges34 bronze badges

C Program To Count Number Of Same Characters In A String

Your regular expression should be btrueb to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:

Make sure the System.Text.RegularExpressions namespace is included at the top of the file.

StuartLC
85.9k15 gold badges148 silver badges212 bronze badges
DonaldRayDonaldRay

This will fail though if the string can contain strings like 'miscontrue'.

Sangram Nandkhile
8,58415 gold badges70 silver badges103 bronze badges
SploofySploofy
Jace RheaJace Rhea
4,1743 gold badges31 silver badges55 bronze badges

C Program To Count Repeated Character In A String Crossword Clue

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

RobaticusRobaticus
20.7k4 gold badges50 silver badges65 bronze badges

do this , please note that you will have to define the regex for 'test'!!!

VoodooChildC program to count repeated character in a string crosswordVoodooChild
8,2926 gold badges56 silver badges95 bronze badges

Not the answer you're looking for? Browse other questions tagged c#stringcount or ask your own question.