|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Be the architects of evolution and help create the mobile internet future. It’s your move---enter to win here! |
|
#1
|
||||
|
||||
|
string letter detection?
Is there a way that I can tell if a string has a certain letter in it? For example:
string asdfa; cout<<"type in string"; cin>>asdfa; if...(there is the letter 'a' in string) { cout << "Your string contained the letter 'a' which isn't allowed in my program"; } else if (if there isn't letter 'a' in string) { continue... } So I guess I am askign if there is a way I can detect a letter in a string and react based on if the user has typed that letter or not. Thanks! -andy
__________________
hmmm... |
|
#2
|
||||
|
||||
|
Use strchr() or strstr()
|
|
#3
|
||||
|
||||
|
hmm not formiliar with those..ill do some research. Thanks!
-andy |
|
#4
|
|||
|
|||
|
andy3109,
Those functions are going to implement a process whereby you examine each character in the string using array notation. Using the string length as the loop control, you can examine each character of the string like this: Code:
string text;
char looking_for = 'a';
bool found_flag = false;
for(int i=0; i<text.length(); i++)
{
if(text[i]==looking_for)
{
found_flag=true;
break;
}
}
|
|
#5
|
||||
|
||||
|
Use the STL:
Code:
#include <algorithm>
std::string::size_type pos =0;
pos = asdfa.find_first_of("x", 0); // find "x"
if (pos == std::string::npos)
// nope
else
// found
|
|
#6
|
||||
|
||||
|
hmm..both interesting ways..I understand 7stud more, but thanks for your reply vpopper!
-andy |
|
#7
|
||||
|
||||
|
what if you wanted to text a rage of letters, as A through F.
|
|
#8
|
|||
|
|||
|
All characters are stored as integer codes. You can look up the ASCII codes for all the characters--there's a table of codes in the appendix of my book, so check yours for the table.
ASCII codes for A-F are 65-70, so you can test whether text[i] is between 65 and 70. Last edited by 7stud : February 25th, 2003 at 08:52 PM. |
|
#9
|
||||
|
||||
|
got it to work..thanks man.
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > string letter detection? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|