我做了一个练习,说:
写一个程序,可以将字母与单词分开,然后用Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel取代字母Juliet Kilo Lima Mike 11月Oscar Papa魁北克罗密欧Sierra Tango制服Victor Whiskey Xray Yankee Zulu(a = Alpha B = bravo等)和带*的数字(1 = * 2 = ** 3 = ***等)。
让我们说我要打破句子"你好2你!"。
我希望我的程序返回:
Hotel Echo Lima Lima Oscar ** Yankee Oscar Uniform!.
如何编写程序来执行此操作?
答案 0 :(得分:0)
以下程序只是众多可能的一项,应该为您提供解决方案的想法:
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char * alphaTable[] = {
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliet",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"Xray",
"Yankee",
"Zulu",
NULL
};
void strtoupper(char *s)
{
while (*s)
{
if ((*s >= 'a') && (*s <= 'z'))
*s -= ('a'-'A');
s++;
}
}
char * findMatch(char *table[], char c)
{
int i;
for(i=0; table[i] != NULL; i++)
{
if ( table[i][0] == c) // if first character matches
{
return table[i];
}
}
return NULL;
}
int printConvertedText(char *input)
{
int i;
strtoupper(input); // convert all letters to caps
for (i=0;input[i]!=0;i++)
{
// take characters from the input string
char c = input[i];
// and find matching first letter in the alphaTable
char * result = findMatch(alphaTable,c);
if(result)
{
printf(" %s",result);
}
else // NOT A LETTER
{
if (isdigit(c)) // number
{
int num = c-'0'; // a short cut: get a number
int j;
printf(" ");
for(j=0;j<num;j++) // nothing printed for 0!
{
printf("%s","*");
}
}
else // everything else is printed as is
{
printf("%c",c);
}
}
}
return 0;
}
int main()
{
size_t bytes_read = 0;
size_t nbytes = 1000;
char *my_string;
// this works for given string:
// char input [] = "Hello 2 you!.";
// printConvertedText(input);
puts ("Please enter a line of text: ");
my_string = (char *) malloc (nbytes + 1); // alocate memory for input
bytes_read = getline (&my_string, &nbytes, stdin); // get the input
if (bytes_read == -1)
{
puts ("ERROR!\n");
}
else
{
puts ("You typed:");
puts (my_string);
puts ("After conversion:");
printConvertedText(my_string);
}
return 0;
}
//输出:
Please enter a line of text:
hello2 you!!.
You typed:
hello2 you!!.
After conversion:
Hotel Echo Lima Lima Oscar ** Yankee Oscar Uniform!!.
您可以运行代码here