Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search for a character in a sentence

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Does anybody know what command should I put to allow Ms C++ 6.0 to search for a certain character inside a sentence.
Ex: (My name is Tim)
The character I want to search for is 'a'.
If found it tell me that you found 1 a.
If found more than one tell me that you found 2 a.
If did't find any tell me cannot find.

Thanks
 
I know that there is a special function for these but you might also try the following code that i have wrote:

#include <iostream.h>
#include <stdio.h>
void FindCharacter( char *Sentance, char character )
{
int count = 0;
int i = 0;
while( Sentance != '\0' )
{
if( Sentance == character )
count++;
i++;
}
cout<<count<<character<<&quot; have been found !\n&quot;;
}

void main()
{
char c;
char Sentance[100];
cout<<&quot;Enter a sentance:&quot;<<endl;
gets( Sentance );
cout<<&quot;What character do you want to search for ?&quot;<<endl;
cin>>c;
FindCharacter( Sentance, c );
}

I hope that this will help !
 
Well, I would take a different approach. I would use &quot;qsort&quot; on the sentence and write up a compare function. qsort will sort the letters based upon your compare function. Once completed, you can go through the array and know that if a character is found, you can just move up your index by one until you are no longer at that character. the built in function &quot;bsearch&quot; may also be helpful as it will give you the first location of the character or strtok may be another way to go without any sorting what so ever.

Matt
 
That is really cool. I just ran it. A few questions.

1)while( Sentance != '\0')
Does '\0' mean &quot;last item in a pointer&quot;?

2)cout<<count<<character<<&quot; have been found !\n&quot;;
Is !\n the same thing as <<endl?

3)gets( Sentance );
This one really interests me. So... this built-in function basically takes the everything you enter and stores it a pointer?

4)Finally, is Sentance an array or a pointer?
 
1)No,it is the last item in a string.

2)yes they are equivalent.

3)yes,or it can stores it in away also.

4)When i first use it in 'FindCharacter' it was pointer but later when i had use it inside 'void main' it was an array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top