How to count number of occurances in a text string

Hi Guys,
I’m new to visual basic 2008 (Trying to write desktop apps for work) and would like to know how to count the number of occurances of a character or substring in a string.

I know how test test if the character is there, but can’t find any documentation on how to count them if there’s more than 1.

If anyone can point me in the right direction I’d really appreciate it.

thanks

Kind regards
Steve

found a solution:

        Dim myMatches As MatchCollection
        Dim myPattern As New Regex(":")
        Dim myString As String = TextBox1.Text
        myMatches = myPattern.Matches(myString)

        ' Search for all the matches in the textbox
        Dim successfulMatch As Match
        Dim counter As Integer = 0
        For Each successfulMatch In myMatches
            counter = counter + 1
        Next

How about something like this:

string textString = "kljskjfsd:kljlksdjf:kjsdfh:";
int textCount = textString.Count(c => c == ':');

textCount equals 3 in this case. That only works for Char and not string though.

edit: try this for counting string in a string [highlight=“c#”]textCount = textString.Select((c, i) => textString.Substring(i)).Count(sub => sub.StartsWith(“skj”));

This will count multiple strings and substrings, if that is a requirement.

"89|43h93::hgjfo::josd.fjfa8j".Split(new string[".", "::", "|"] {}).Count - 1

Cheers,
D.

Thanks for the alternative solutions guys.

NAWA-mark I’m a little unfamiliar with visual basic so this might be a silly question, but can I mix c sharp and visual basic code?

disgracian could you explain your code please:

It appears as though your providing a string (But am I correct that you could simply provide a variable or textbox1.text for example?)

Where you have writting new string, does the code mean that it will create a new string whereever a character in the square brackets appears? (excluding the square brackets presumably)

What are the empty curley brackets for?

And what is the minus 1 for at the end of the count?
Is it to take account for array indexes being zero based and not one based?
So it’s putting everything into an array, getting the count of the array and -1?

Why not use the .length method?

Sorry for all the questions, I’d just rather learn than simply copy and paste.

While we’re on the topic of string manipulation, how can I specify a string, and return everything after the final backslash, (exactly like find and replace “*\” in excel).
I guess you should split by slashes, put it into an array somehow (a little rusty on array manipulation), count the number of items in the array, minus 1 and return that item.

I found a super easy way to find the number of occurances of a string in a string (delimited by “test”):


        Dim mysplit As Array
        mysplit = Split(TextBox1.Text, "test")
        MsgBox(mysplit.Length - 1)

Found out how to get the last item of an array like how I requested:


        Dim mysplit As Array
        mysplit = Split(TextBox1.Text, "\\")
        Dim lastArrayItemNumber As Integer
        lastArrayItemNumber = mysplit.Length - 1
        MsgBox(mysplit(lastArrayItemNumber))

One thing that I was having trouble with was the split method.
What’s the difference between:
textbox1.text.split(“test”)
and
split(textbox1.text,“test”)

?

I should probably rewrite it to remove the syntax error I only just noticed.

"89|43h93::hgjfo::josd.fjfa8j".Split(new string[] { ".", "::", "|" }).Count - 1;

I suppose I probably should have written it out more explicitly.

string text = "89|43h93::hgjfo::josd.fjfa8j";
string[] substringsToCount = new string[] { ".", "::", "|" };

int count = text.Split(substringsToCount).Count - 1;

And what is the minus 1 for at the end of the count?
Is it to take account for array indexes being zero based and not one based?

It’s because Split will return an array containing the entire input text if no matching tokens were found, and the array’s count will therefore always be >= 1.

Why not use the .length method?

Length returns the number of characters in a string, which is not useful here. If you really wanted to use Length, you could do something like this:

int count = Regex.Replace(inputString, @"[^\\.:]", string.Empty).Length;

The ‘@’ preceding the string tells the C# compiler to treat the string literally and proccess the backslashes as backslashes rather than use them to denote special characters (eg., "
" is a newline character). Using ‘^’ negates the characters in the square brackets. I won’t go into detail on the rest, as regular expressions are a topic in itself.

Sorry for all the questions, I’d just rather learn than simply copy and paste.

I applaud this. It’s a rare attitude on these forums.

While we’re on the topic of string manipulation, how can I specify a string, and return everything after the final backslash, (exactly like find and replace “*\” in excel).
I guess you should split by slashes, put it into an array somehow (a little rusty on array manipulation), count the number of items in the array, minus 1 and return that item.

The string object has a LastIndexOf method, I believe. Combined with Substring, it could prove quite useful.

Cheers,
D.