473,394 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to find total count of a character in a string

37
Hi All,

How can i find the total 'Count' of a particular character's occurance in a string.

means i want to find the count of '<' in a string.

can you please help to find that.

Thanks
Dec 2 '08 #1
9 4116
Plater
7,872 Expert 4TB
So if you had the string: "fred<ran<fast<" and looking for count of "<"
You would want the number 3 to be returned?
I think a regex can do this, you tell it to match that character and return a set of matches, and the number of matches will tell you the number of occurances?
Dec 2 '08 #2
Curtis Rutland
3,256 Expert 2GB
Well, if you want to keep things simple...

String has a ToCharArray method. Use it, then loop through the array, incrementing a counter every time that you encounter the specific char.

Expand|Select|Wrap|Line Numbers
  1. string CountCharInstances(string s, char c)
  2. {
  3.   char[] ch = s.ToCharArray();
  4.   int count = 0;
  5.   for(int i=0; i<ch.Length; i++)
  6.     if(ch[i] == c)
  7.       count++;
  8.   return count;
  9. }
Dec 2 '08 #3
balabaster
797 Expert 512MB
I way prefer regex for this. I'll use Plater's test string as InputString, and ">" as my SearchString variable.
Expand|Select|Wrap|Line Numbers
  1. int Count = Regex.Matches(InputString, SearchString).Count;
But a simple split would also suffice:
Expand|Select|Wrap|Line Numbers
  1. int Count = InputString.Split(SearchString).Count - 1;
Dec 2 '08 #4
Curtis Rutland
3,256 Expert 2GB
I don't think that split will work, if the character starts or ends the string. But the Regex answer is much more elegant than mine.
Dec 2 '08 #5
Plater
7,872 Expert 4TB
Yes, I don't normally suggest a regex right off, but if the input string was thousands and thousands of characters, iterating through manually would be tedious.
Dec 2 '08 #6
balabaster
797 Expert 512MB
@insertAlias
Well in the tests I ran it works in both cases. I used the following SearchString: "<fred<ran<fast<<<"

Split.Count - 1 provided the same result as Regex.Match.Count

Obviously you need to take into account that the purpose of split is to find the strings between the chars and not the chars themselves. But handily [is that a word?], in cases where you've got adjacent search characters it provides "" as the string between them in the array. So you'll always end up with n+1 where n is the value you're looking for.

So in cases where you don't fully understand Regex - split will work nicely as a "dirty but elegant" solution - if such a thing could exist.
Dec 2 '08 #7
balabaster
797 Expert 512MB
@Plater
How does the anecdote go? Sometimes you'll have a problem and you think "I know, I'll use a regular expression". Now you've got two problems...
Dec 2 '08 #8
balabaster
797 Expert 512MB
You could also do it with LINQ:

Expand|Select|Wrap|Line Numbers
  1. int Count = InputString.Where(c => c = SearchString).Count;
It doesn't perform as well as regex or split though, so while it's amusing to come up with as many variant ways of performing this task with minimal code, it's probably not the choice to use in this case.

You could just do a plain old count using a predicate. This one actually appears to perform as well as split and regex and is probably the right way to go. It is more intuitive to someone reading your code as to what it's purpose is at a glance:
Expand|Select|Wrap|Line Numbers
  1. int Count = InputString.Count(CurrentChar => CurrentChar = SearchChar);
Another dirty but performant solution:
Expand|Select|Wrap|Line Numbers
  1. int Count = InputString.Length - InputString.Replace(SearchString, String.Empty).Length;
Dec 2 '08 #9
Curtis Rutland
3,256 Expert 2GB
OK, I didn't realize that Split returned empty strings by default, good stuff to know.
Dec 2 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: fwells11 | last post by:
Hi there. As you will see from my questions, I am an SQL newb. I dabble but never get to spend enough time to get proficient so base any feeedback on that basis please. This is all theoretical...
10
by: Craig Bumpstead | last post by:
Hi, I was wondering the best and fastest way to determine how many lines are in a log file. At the moment I am simply doing a StreamReader.ReadLine and incrementing a counter until I reach...
2
by: worli | last post by:
Hi All, I have a strange requirement. I have a dynamic input numeric data stream e.g. 2, 2, 4, 5 etc.... ( each input number range from 1 to 10 ). lets take a simple case where all inputs will...
10
by: Jon | last post by:
I want to count the number of instances of a certain string(delimiter) in another string. I didn't see a function to do this in the framework (if there is, please point me to it). If not, could...
3
by: Kuups | last post by:
Hi! I have a question regarding the count if character within a string like for example I have a string of e.g. 123#123# I would like to determine what is the code? of getting the # sign
19
by: ashmangat | last post by:
Hi! now on the chapter "string-class" My assignment is below Word Counter: Write a function that accepts a pointer to a C-String as an argument and returns the number of words contained in the...
7
by: idle | last post by:
#include<stdio.h> int count (char letter, const char *my_string); void main() { int total_l; char my_string = “walla la oh la la la la la long”; char letter = ‘l’; total_l = count(letter,...
1
by: vmoreau | last post by:
I have a text and I need to find a Word that are not enclosed in paranthesis. Can it be done with a regex? Is someone could help me? I am not familar with regex... Example looking for WORD:...
1
by: eraserwars | last post by:
My compiler keeps saying LNK2019, and my teacher says to look for spelling error. He says that most likely what is happening is that a spelling error is messing my program up. I searched, and I did...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.