473,399 Members | 4,177 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,399 developers and data experts.

Count all occurrences of a character in a string

344 100+
Hello,

Very easy task, I know :)

Searching the internet for a simple .NET method to do that for me brought to me this page inside Bytes.com: Count all occurrences of a character in a string

I think they have come with working solutions, but why writing a method or a loop to do this simple task.

It came to my mind that removing the character from the string will decrease the string Length with the character occurrence. Good but .NET does not have that Remove(char) Method, alright we can use Replace(char, char) or Replace(string, string). Lets do that.

Lets say we have a string called search and a char called c.
Expand|Select|Wrap|Line Numbers
  1. int occurrence = search.Length - 
  2.          search.Replace(c.ToString(), string.Empty).Length;
Subscribing the string after the characters are removed (or replaced with nothing) from the original string will result the occurrence. Very simple, one line.


I hope it will work for someone!


Regards,
Bassem
May 15 '10 #1
12 16859
tlhintoq
3,525 Expert 2GB
Why would you replace anything in a string just to count the occurances of a character?

What problem is this "insight" supposed to solve? Counting the characters in a string is about 5 lines of code.

This also only works if you are looking for a single character. What if you are looking for a 3 character combo?

How often are you really looking for just 1 character in a string? May I suggest something a bit more universal? This will let you search for 1 or more characters out of a string, and return the positions of all the matches.

Expand|Select|Wrap|Line Numbers
  1.         private void button1_Click(object sender, EventArgs e)
  2.         {
  3.             string SearchFor = "abc";
  4.             string SearchIn = "abc123jklabc789yuihjabc789cdsjkleifkbkc125abc";
  5.             List<int> FoundCount = Search(SearchFor, SearchIn);
  6.  
  7.             MessageBox.Show(FoundCount.Count.ToString(), "Count of matches");
  8.         }
  9.  
  10.         List<int> Search(string Target, string Subject)
  11.         {
  12.             List<int> Results = new List<int>();
  13.             for (int Index = 0; Index < (Subject.Length - Target.Length) + 1; Index++)
  14.             {
  15.                 if (Subject.Substring(Index, Target.Length) == Target) Results.Add(Index);
  16.             }
  17.             return Results;
  18.         }
  19.  
May 15 '10 #2
Bassem
344 100+
Hello tlhintoq,

Thank you for reading my post!

1. I didn't replace anything in the original string, it is another copy of it.

2. The main purpose of my post, is to avoid loops in getting the occurrence count of a character in a string.

Very important idea, that one of counting an occurrence of a string. I think my solution solve this one too, does not it?!

Finally, what I focused on through my post - again - avoiding loops, but I see one in your solution :)


Thank you for your interest!
May 15 '10 #3
tlhintoq
3,525 Expert 2GB
Oh... The goal was to avoid loops. Ok. That was never mentioned in the actual post. You even rhetorically ask about using a loop

I think they have come with working solutions, but how write a method or a loop to do this simple task.

That is why I asked.
May 15 '10 #4
Bassem
344 100+
Forgive my mistake, I wanted to type "why writing" not "how".

Thanks a lot tlhintoq for reading my posts you give them a value.
May 15 '10 #5
Curtis Rutland
3,256 Expert 2GB
Here's the simplest way I found to do this using LINQ:
Expand|Select|Wrap|Line Numbers
  1. int count = "*** test ***".ToCharArray().Where(x => x == '*').Count(); //count == 6
Technically, there is a loop here that's being obfuscated. The "Where" extension method actually loops through the array for each value (assigning it to "x", the parameter for the method we're shortcutting with a lambda) and stores it in an IEnumerable if the char == '*'. But that's all obfuscated, and what you end up with is a simple one-line code.
May 17 '10 #6
Bassem
344 100+
Good idea, and logical than mine!
I think even my solution the .NET framework uses a loop to replace the occurrence - I've no idea just a thought - but I don't that how I see it simple. Ideally, I was searching for the shortest way to do that.
May 17 '10 #7
GaryTexmo
1,501 Expert 1GB
I don't mean to be rude or anything (so please don't read it as such!) but it seems to me that going through all the trouble to eliminate a loop in code by using things that do loops anyway seems a little pointless.

Don't get me wrong here, using pre-made stuff (ie, the bulk of .NET!) over doing it yourself is great, but you also get disconnected a little from what's going on. I know I sometimes like to expand something just to make sure I'm keeping track of it in my head.

This is me though, and there's absolutely nothing wrong with the above, I think this thread is a fairly simple case... all I'm saying is just keep in mind the poor individual who gets to come along behind you in a few years and debug your code when you strive to save line space using techniques like this ;)
May 17 '10 #8
Curtis Rutland
3,256 Expert 2GB
I do occasionally think about that poor sucker...I mean colleague that may have to read my code.

But I guess it's all about style and preference, which should be decided upon and followed at your company. To me, the one-line LINQ statements are easier than the expanded versions, or writing loops and ifs, because they are pretty verbose about what they are doing. They have names like First, Take, and Where. They flow left to right (the same direction you read english).

But I don't disagree with you. Sometimes its more efficient to do things all at once together, but it doesn't always lend itself to readability.

I just realized how much I have to be seeming like the LINQ guy, because practically all my solutions involve it. It's not that I'm so into it...it's just that it's that darn convenient. Once you learn it, you love it.
May 17 '10 #9
jkmyoung
2,057 Expert 2GB
In the interest of code clarity and re-usability, I would just make it a function:
int numberOfCharOccurrences(String s, char c)
then it would look like a clear, one line solution, even though some of the code was elsewhere.
May 17 '10 #10
GaryTexmo
1,501 Expert 1GB
I don't disagree with you either... thus I believe we're in not incomplete non-disagreement!!

:P

(I just wanted to point that out... I've seen a lot of programmers be obsessed about line count savings. These days, it's just not terribly important imo. Also, I love your LINQ solutions, I learn something almost every post of yours I read. Keep it up!)
May 17 '10 #11
Christian Binder
218 Expert 100+
There's a shorter way to do it with LinQ:
The count-method takes a predicate to check if an item should be counted, so you can reduce
Expand|Select|Wrap|Line Numbers
  1. int count = "*** test ***".ToCharArray().Where(x => x == '*').Count(); //count == 6
to
Expand|Select|Wrap|Line Numbers
  1. int count = "*** test ***".ToCharArray().Count(x => x == '*'); //count == 6
This would eliminate a loop, because (as far as I know) Where() and Count() will loop over the IEnumerable<char>.
May 25 '10 #12
Curtis Rutland
3,256 Expert 2GB
That's pretty good. I never used count to count a specific character, always just to count total characters. Your way does actually work better.
May 25 '10 #13

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

Similar topics

0
by: MLH | last post by:
Is an apostrophe a character of special significance to MySQL in a way that would cause "Bob's dog" to become translated into a 12-character string when typed into a MySQL memo field? If I type...
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
7
by: Justin | last post by:
i need to build the unsigned character string: "PR0N\0Spam\0G1RLS\0Other\0Items\0\0\0" from the signed character string: "PR0N Spam G1RLS Other Items" Tokeninzing the character string is not...
5
by: Karthik | last post by:
Hello! I am not a wizard in this area! Just need some help out in this. I am trying to convert bstr string to new character string. Here is the snippet of my code. **** Code Start**** ...
25
by: lovecreatesbeauty | last post by:
Hello experts, I write a function named palindrome to determine if a character string is palindromic, and test it with some example strings. Is it suitable to add it to a company/project library...
8
by: Brand Bogard | last post by:
Does the C standard include a library function to convert an 8 bit character string to a 16 bit character string?
3
by: Dana King | last post by:
I'm looking for some other developers opinions, I'm trying to find the best way to count strings within a string using VB.net. I have tested five methods and have found the String.Replace method...
4
by: thomas | last post by:
I have a list of strings composed of only 0 and 1, like 0000100001 1000010000, .... They all have the same length. Now they are stored in a vector of strings. I want to calculate count(string1...
4
by: arulk | last post by:
Can we count wraping Character in xsl? character reading from xml.... anyone know this can send me sample code ...
0
by: dougancil | last post by:
I have the following code: Imports System.Data.SqlClient Public Class Main Protected WithEvents DataGridView1 As DataGridView Dim instForm2 As New Exceptions Private Sub...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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.