Converting Letters to Numbers in C

前端 未结 10 1205
悲&欢浪女
悲&欢浪女 2020-11-30 07:22

I\'m trying to write a code that would convert letters into numbers. For example A ==> 0 B ==> 1 C ==> 2 and so on. Im thinking of writing 26 if statements. I\'m wondering

10条回答
  •  抹茶落季
    2020-11-30 07:36

    In most programming and scripting languages there is a means to get the "ordinal" value of any character. (Think of it as an offset from the beginning of the character set).

    Thus you can usually do something like:

    for ch in somestring:
        if lowercase(ch):
            n = ord(ch) - ord ('a')
        elif uppercase(ch):
            n = ord(ch) - ord('A')
        else:
            n = -1  # Sentinel error value
            # (or raise an exception as appropriate to your programming
            #  environment and to the assignment specification)
    

    Of course this wouldn't work for an EBCDIC based system (and might not work for some other exotic character sets). I suppose a reasonable sanity check would be to test of this function returned monotonically increasing values in the range 0..26 for the strings "abc...xzy" and "ABC...XYZ").

    A whole different approach would be to create an associative array (dictionary, table, hash) of your letters and their values (one or two simple loops). Then use that. (Most modern programming languages include support for associative arrays.

    Naturally I'm not "doing your homework." You'll have to do that for yourself. I'm simply explaining that those are the obvious approaches that would be used by any professional programmer. (Okay, an assembly language hack might also just mask out one bit for each byte, too).

提交回复
热议问题