The function strchr() scans a string for the first occurrence of a given character; strchr() returns a pointer to the first occurrence of the character c in s; if c does not occur in s, strchr returns null. This could be used for something like the following.
Code:
#include <stdio.h>
#include <string.h>
char Digit(char ptr)
{
if(strchr("ABCabc", ptr)) return('2');
else if(strchr("DEFdef", ptr)) return('3');
else if(strchr("GHIghi", ptr)) return('4');
else if(strchr("JKLjkl", ptr)) return('5');
else if(strchr("MNOmno", ptr)) return('6');
else if(strchr("PQRSpqrs", ptr)) return('7');
else if(strchr("TUVtuv", ptr)) return('8');
else if(strchr("WXYZwxyz", ptr)) return('9');
return(ptr);
}
int main(void)
{
const char number[] = "1-800-COLLECT", *ptr;
puts(number);
for(ptr = number; *ptr; ++ptr)
{
putchar(Digit(*ptr));
}
return(0);
}
/* my output
1-800-COLLECT
1-800-2655328
*/
Another way might be as follows.
Code:
#include <stdio.h>
#include <string.h>
char Digit(char ptr)
{
const char *Letter[] =
{
/* 2 */"ABCabc",
/* 3 */"DEFdef",
/* 4 */"GHIghi",
/* 5 */"JKLjkl",
/* 6 */"MNOmno",
/* 7 */"PQRSpqrs",
/* 8 */"TUVtuv",
/* 9 */"WXYZwxyz",
};
size_t i;
for(i = 0; i < sizeof(Letter)/sizeof(*Letter); ++i)
{
if(strchr(Letter[i], ptr))
return(i + '2');
}
return(ptr);
}
int main(void)
{
const char number[] = "1-800-COLLECT", *ptr;
puts(number);
for(ptr = number; *ptr; ++ptr)
{
putchar(Digit(*ptr));
}
return(0);
}
/* my output
1-800-COLLECT
1-800-2655328
*/