I am trying to create a system that gets a string from the user and converts it to an integer. I want an integer representation for each letter, that way any string can be converted to an integer. I have tried putting each character of the string into an array, and then checking one by one for every letter. That method became to messy, so I was wondering if there was also a shorter way of doing this.
Asked
Active
Viewed 202 times
-2
-
`String.hashCode()`? (Just don't expect any scheme you come up with to produce a *unique* integer, unless you're willing to go with `BigInteger`) – nneonneo Jun 10 '14 at 15:34
-
What is the integer reprsentation of a letter in your case? – Jens Jun 10 '14 at 15:35
-
http://stackoverflow.com/questions/16458564/convert-string-to-ascii-value-in-java – RobEarl Jun 10 '14 at 15:36
3 Answers
2
I want an integer representation for each letter
- Use
String
to get Character Array by the use of"yourString".toCharArray();
- Use ForEach loop to get int for every character.
for(char c:yourstring.trim().toCharArray())
{
int a=(int)c;
arrayList.add(a); //store integers to arrayList or array as you wish
}

Anubian Noob
- 13,426
- 6
- 53
- 75

akash
- 22,664
- 11
- 59
- 87
-
-
2
-
1I guess it works, but keep in mind that it's not unique. Also it can overflow. Just things to keep in mind, this works fine. – Anubian Noob Jun 10 '14 at 15:44
1
If you want to convert a string to an integer you can try doing the following:
int c = Integer.parseInt("Your String");
For converting a letter to a string you can try the following:
String word = "abcd";
StringBuilder build = new StringBuilder();
for (char c : word.toCharArray()) {
build.append((char)(c - 'a' + 1));
}
So basically you subtract to find the integer value of the letter. NOTE: this only works for strings that are all in lower case. If you have letters in upper case you will have to convert them to lower case before applying the above.

selena
- 151
- 13
-
Don't forget that this method throws a NumberFormatException, so the statement must be enclosed in a try-catch block or the method that this line would be in must throw NumberFormatException. – jluckin Jun 10 '14 at 15:39
-
This will throw an exception. The asker's string contains letters. – ban-geoengineering Jun 10 '14 at 15:43
1
Maybe the getNumericValue() method of Character is what you are after? You could use it in a loop.

ban-geoengineering
- 18,324
- 27
- 171
- 253