21

I'm quite new to Java so I am wondering how do you convert a letter in a string to a number e.g. hello world would output as 8 5 12 12 15 23 15 18 12 4.
so a=1, b=2, z=26 etc.

1
  • OP wants to map each letter to its position in the alphabet. Thats how I understood it.
    – Booyaches
    Feb 22, 2013 at 15:18

9 Answers 9

75

Since this is most likely a learning assignment, I'll give you a hint: all UNICODE code points for the letters of the Latin alphabet are ordered alphabetically. If the code of a is some number N, then the code of b is N+1, the code of c is N+2, and so on; the code of Z is N+26.

You can subtract character code points in the same way that you subtract integers. Since the code points are alphabetized, the following calculation

char ch = 'h';
int pos = ch - 'a' + 1;

produces the sequence number of h, i.e. 8. If you perform this calculation in a loop, you would get the result that you need.

Note that the above formula works only with characters of the same register. If your input string is in mixed case, you need to convert each character to lower case before doing the calculation, otherwise it would come out wrong.

1
2

If you need you can use below tested code to convert string into number if your string contains only numbers and alphabets.

 public static Long getNumericReferenceNumber(String str) {

        String result = "";

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (Character.isLetter(ch)) {
                char initialCharacter = Character.isUpperCase(ch) ? 'A' : 'a';
                result = result.concat(String.valueOf((ch - initialCharacter + 1)));
            } else result = result + ch;
        }

        return Long.parseLong(result);
    }
1
String s = "hello world";
String t = "";
for (int i = 0; i < s.length(); ++i) {
    char ch = s.charAt(i);
    if (!t.isEmpty()) {
        t += " ";
    }
    int n = (int)ch - (int)'a' + 1;
    t += String.valueOf(n);
}
System.out.println(t);

This does not deal with space etc.

1
public static void main(String[] args) {
    String s = "hello world";
    s = s.replace(" ", "");
    char[] c = s.toCharArray();

    for (Character ss : c)
        System.out.println(ss - 'a' + 1);
}
1

for each character at posotion i: output s.charAt(i)-'a'+1. s is the string.

0

You can do something like:

for (int i = 0; i < a.length(); ++i) {
  if (a.charAt(i) >= 'a' && a.charAt(i) <= 'z') {
    System.out.println((int)a.charAt(i) - (int)'a');
  } 
}
0

Usa a Map with the key being the character and an value being the integers. This is not an efficient way - the map should be a static member of the class.

import java.util.HashMap;
import java.util.Map;


public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        final Map<Character, Integer> map;
        final String str = "hello world";

        map = new HashMap<>();  
        // or map = new HashMap<Character, Integer> if you are using something before Java 7.
        map.put('a', 1);
        map.put('b', 2);
        map.put('c', 3);
        map.put('d', 4);
        map.put('e', 5);
        map.put('f', 6);
        map.put('g', 7);
        map.put('h', 8);
        map.put('i', 9);
        map.put('j', 10);
        map.put('k', 11);
        map.put('l', 12);
        map.put('m', 13);
        map.put('n', 14);
        map.put('o', 15);
        map.put('p', 16);
        map.put('q', 17);
        map.put('r', 18);
        map.put('s', 19);
        map.put('t', 20);
        map.put('u', 21);
        map.put('v', 22);
        map.put('w', 23);
        map.put('x', 24);
        map.put('y', 25);
        map.put('z', 26);

        for(final char c : str.toCharArray())
        {
            final Integer val;

            val = map.get(c);

            if(val == null)
            {   
                // some sort of error
            }
            else
            {
                System.out.print(val + " ");
            }
        }

        System.out.println();
    }
}
3
  • +1 for detailed explanation. BDW this question was asked to me in the interview I answered using the same approach. :)
    – amod
    Mar 18, 2013 at 12:41
  • I don't understand why you would do it this way. "This is not an efficient way" = there is a better way - what is it?
    – Menasheh
    Feb 27, 2017 at 5:47
  • It is an easy to understand way. If it is not used very frequently then the efficiency doesn't matter. Goal #1 is make it correct, Goal #2 is make easy to understand/maintain, goal #3 is make it fast. If you have other goals they probably get inserted between #2 and #3. Speed is, generally, not that important, in that you can find out where your code is slow and then decide how best to speed it up.
    – TofuBeer
    Mar 1, 2017 at 9:05
0

I have added all the characters to get a fair result:

public static long stringToNumber(String s) {
    long result = 0;

    for (int i = 0; i < s.length(); i++) {
        final char ch = s.charAt(i);
        result += (int) ch;
    }

    return result;
}
0

Consider any string as a number of base x, where x is the length of the alphabet used to describe that string, then convert that number to another number of base 10. Google for an algorithm that deals with number bases conversions.

If we adopted the English keyboard layout, the x here could equal to 26+26+10+1(space)+y ,where y is the number of special characters.

The most common example of that is converting from Hex, base 16, to decimal, base 10 and from binary to decimal and so on.

Not the answer you're looking for? Browse other questions tagged or ask your own question.