-2

I got this array of string

String s1[] = {"H","E","L","L","O"};

and a method to convert it into int

    public static int[] String2Int(String[] k){
    int[] arrayBuffer = new int[k.length];

    for (int i=0; i < k.length; i++)
    {
        //arrayBuffer[i] = Integer.parseInt(k[i]);
        arrayBuffer[i] = Integer.parseInt(k[i]);
    }
    return arrayBuffer;

I want the decimal values of the characters but no luck on getting it. Google is only helping with if the string were a number.

Tor
  • 19
  • 3

3 Answers3

2

You shouldn't convert it to integer. It should be

 arrayBuffer[i] =k[i].charAt(0);

That way you get the ASCII value of char and gets assigned to int.

Edit :

You can also use arrayBuffer[i] = Character.codePointAt(input, 0); as pointed in comments.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Try this:

class MainClass
{
    public static void main(String[] args)
    {
        System.out.println(Arrays.toString(String2Int("HELLO")));
    }
    public static int[] String2Int(String k)
    {
        int[] arrayBuffer = new int[k.length()];

        for (int i = 0; i < arrayBuffer.length; i++)
        {
            //arrayBuffer[i] = Integer.parseInt(k[i]);
            arrayBuffer[i] = k.charAt(i);
        }
        return arrayBuffer;
    }
}

Output:

[72, 69, 76, 76, 79]

Explanation

char and int is almost the same in Java. You don't need to parse it, you just implicitly cast it by asigning it to the int[]. Also you shouldn't take a String[] as an argument, that makes no sense. A String is already almost a char[]. So either take a String, or a char[]. In my example I've used a String because that is more convenient to call.

Impulse The Fox
  • 2,638
  • 2
  • 27
  • 52
0

Using the Java 8 Stream API:

public static int[] convert(String[] strings)
{
    Objects.requireNonNull(strings);
    return Arrays.stream(strings)
            .mapToInt(str -> Character.getNumericValue(str.charAt(0)))
            .toArray();
}

I assume you dont need to check that the input strings contain exactly one character.

sn42
  • 2,353
  • 1
  • 15
  • 27