String count (How To)

pluton

Active Member
Licensed User
Longtime User
Hi everyone

I have a little task and my brain today has stop. (Summer is crazy :) )

How will I count how many cat and apple is in sentence. (not cats or apples)

I have string:
"This cat is nice and she love apple but other cats don't. Maybe this cat will love more apples and she will be happy cat."

So here we have 3 "cat" and 1 apple
Anyone help with this string count. How to? The best way?
 

mc73

Well-Known Member
Licensed User
Longtime User
Don't search for 'cat', but for ' cat ' (space in the beginning and in the end), when in the middle of the sentence. If in the beginning or the end, search for 'cat ' and ' cat' respectively.
 
Upvote 0

pluton

Active Member
Licensed User
Longtime User
Don't search for 'cat', but for ' cat ' (space in the beginning and in the end), when in the middle of the sentence. If in the beginning or the end, search for 'cat ' and ' cat' respectively.

I know that but how will I count the "cat" ?

I want number of cat in sentence
EDIT:
Nevermind I figure it out. My brain is still on the beach and my body is in office :(

B4X:
Sub numbCount
Dim Words() As String
Words = Regex.Split(" ", sentence)

For x = 0 To Words.Length - 1 
   If Words(x).Contains("cat") Then
      numb = numb + 1
      Label1.Text = numb
   End If
   Next
End Sub
 
Last edited:
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
If you want to count 'cat' but ignore 'cats', the above code will give you wrong answer.
 
Last edited:
Upvote 0

pluton

Active Member
Licensed User
Longtime User
If you want to count 'cat' but ignore 'cats', the above code will give you wrong answer.

Yes I know mc73 but I manage to escape some of stuff.

The task is that must count "cat" and only cat as animal.
Not count = "Cats", "cats"
Count = "Cat", "cat", "cat.","cat,"...and other variations

Thanks for help and tips :)
 
Upvote 0

WizardOz

Member
Licensed User
Longtime User
First, replace all you spaces with "."
Then replace all your "," with "."
You will then have lots of "cat."
(You will nedd the function Replace(Target, Replacement) for this.

To remove the need of checking for upper or lower cases, use .touppercase
This will make all of your text uppercase.

You will then have lots of "CAT." to search for.

There may be a lot more lean way to do this, but as my head also is in the toilet at the moment, thats my to cents...
 
Upvote 0

pluton

Active Member
Licensed User
Longtime User
Thank you all for your helps but you all are complicated everything.

Suppose that I need return that string only changed for example into dog.

Don't worry I needed this for my little one project and I know exactly where the cat will show up so don't need to convert spaces into dots or comas into dots...
:)

I was just wondering if margret wrote some short way String Functions just to simplify this.
BTW
Nice String Functions Margret. It help's me alot in my project :sign0098:
 
Upvote 0
Top