سؤال

How can i convert a phrase which the user gives into numbers but not with ASCII table ? For example, I have the phrase HELLO WORLD and i have an array in wich <> is 0, A is 1, B is 2, etc. please Help ! My problem is that i cannot find a way to compare two arrays. I have started my code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char  text[]={'         ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','.',',',':','?'};
char number[125];

main(){
    int i,j;
    printf("Enter a message to encode:");
    gets(number);
}

but I have problems continouing it

هل كانت مفيدة؟

المحلول

Every char is basically a smaller int. The value is a value from ascii chart that encodes every letter. As you see, the letters are in 2 continuous blocks (one for upper case and one for lower case). So, for your result to be correct, you need to convert all letters to same case. You may use tolower or toupper functions. Then, you just need to subtract the value of letter a, and perform some checkings for special characters.

You may start with this:

   main(){
       int i,j;
       printf("Enter a message to encode:");
       gets(number);
       int codes[125];
       for(int i = 0; i<strlen(number); i++){
           codes[i] = toupper(number[i]) - 'A' + 1;    // note that 'A' represents the code for letter A. 
                                                       // +1 is because you want A to be 1.
       }
   }

Note that it is just a guideline, you need to add another features I explained above. The numerical result resides in codes in this case.

نصائح أخرى

First, add a null character at the end of text:

char  text[]={'         ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','.',',',':','?','\0'};

Use strchr to find the location of the character in text.

for(int i = 0; i < strlen(number); i++){
    int loc = (int)(strchr(text, number[i]) - &text[0]);
    // save the loc in another array or do whatever you want.
}

You should also ensure that there is no invalid character in number('a' in input wont work as text only contains uppercase characters).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top