pmish pmish - 2 months ago 7
Java Question

(Java) Converting String of symbols to single digit integer array

I'm trying to take a String, i.e.

$!#
, convert each individual symbol to its corresponding ASCII value, it here being
36, 33, 35
and then ending up with an array of integers with each single number stored in a separate index, meaning
3, 6, 3, 3, 3, 5
.

In short: From
$!#
to
$,!,#
to
36, 33, 35
to
3, 6, 3, 3, 3, 5


Since I am using Processing (wrapper for Java), my SO-research got me so far:

String str = "$!#";
byte[] b = str.getBytes();

for (int i=0; i<b.length; i++){
println(b[i]);
}


I'm ending up with the ASCII values. The byte array
b
contains
[36, 33, 35]
.

Now if those were to be Strings instead of bytes, I would use String.valueOf(b) to get
363335
and then split the whole thing again into a single digit integer array.

But this all seems not very efficient. Any suggestions?

Answer

Honestly, if I were you, I wouldn't worry too much about "efficiency" until you have an actual problem. Write code that you understand. If you have a problem with efficiency, you'll have to define exactly what you mean: is it taking too many steps? Is it taking too long? What is the size of your input?

Note that the approach you outlined and the approach below are both O(N), which is probably the best you're going to get.

If you have a specific bottleneck inside that O(N) then you should do some profiling to figure out where that is. But you shouldn't bother with micro-optimizations (or shudder premature optimizations) just because you "feel" like something is "inefficient".

To quote from this answer:

...in the absence of measured performance issues you shouldn't optimize because you think you will get a performance gain.

If I were you, I would just use the charAt() function to get each char in the String, and then use the int() function to convert that char into an int. Then you could add those int values to a String (or better yet, a StringBuilder):

String str = "$!#";

StringBuilder digits = new StringBuilder();
for (int i=0; i<str.length(); i++) {
  int c = int(str.charAt(i));
  digits.append(c);
}

Then you could use the split() function to split them into individual digits:

String[] digitArray = digits.toString().split("");
for (String d : digitArray) {
  println(d);
}

Prints:

3
6
3
3
3
5

There are a ton of different ways to do this: you could use the toCharArray() function instead of charAt(), for example. But none of this is going to be any more or less "efficient" until you define exactly what you mean by efficiency.

Comments