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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find a letter in char

Status
Not open for further replies.

hedvule

Programmer
Oct 25, 2004
7
CH
Hello, I have a following problem:
I have a char, which is a mixture of numbers and letters - something like 23H9. How can I obtain from it the letter (in my exemple H).
Please help me, thanks, Hedvika.
 
> I have a char, which is a mixture of numbers and letters - something like 23H9.

i think that you meant a string.
one possible way for the declare it,would be.
Code:
char *str = "23H9";

> How can I obtain from it the letter (in my exemple H).

i'm not sure if i really understand what you meant here.
if,you want to extract the character 'H' from the previous string,you could simply do something like:
Code:
char myChar = str[2];
if you just want to find the position of the character 'H' inside "str", you could use something like:
Code:
char *pStr = strchr( str, 'H' );
int pos = pStr - str;
 
Hi, thanks to you both, unfortunatelly I've explained my problem a little bit unclearly. I'm reading strings from file all of them are mixtures of numbers and letters. I don't know how the particular string looks like - on which position is the letter, and what is it for letter. In any case I need to find them and extract them. The stream looks like this:
12K9 4J87 I34 N2 N 793J etc.
and I need to obtain: K J I N N J

Is it now more clear? Once again, thanks a lot for help.

Hedvika
 
Use a for loop and the isalpha() function, which will return if a character is a letter.
 
put whole sequence in char array (however you read it in)

Code:
char* mystring = "12K9 4J87 I34 N2 N 793J";
int nLen = strlen(mystring);

for(int i = 0; i < nLen; i++)
{
  if(isalpha(mystring[i])
  {
    //use strcat() or whatever else to append this char
  }
}

I forgot where isalpha() is declared, but I'm sure you can find the right header file for that.

BlackDice

 
isalpha is in <ctype.h> (or if you're doing C++) <cctype>
 
Code:
[b]...[/b]
ifstream fin;
fin.open("file.txt");
char ch;
while(cin >> ch)
{
   if(isalpha(ch))
   {
       // it's a letter put it in an array, list or vector
   }
   else
   {
       // it's not a letter -- must be numaric,
       // puncuation or control char
   }
}
[b]...[/b]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top