So I'm new to java and decided to mess around a little, I wrote a class that converts a string to an array made out of the ascii values of the characters in the string, but I don't know how to get the value of the variable i. I know it's easier to use a list but I'm really curious how to make this work. This is the code:
public class ToAscii {
static int[] toAscii(String txt){
int[] array = new int[1000];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch -1;
i++;
}
return array;
}
}
txt.codePoints().toArray()
will convert the String
to codepoints (ie numbers of the characters).
For example:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
System.out.println(Arrays.toString("abc".codePoints().toArray()));
}
}
will print:
[97, 98, 99]
where 97 corresponds to 'a', 98 to 'b' and 99 to 'c'.
The problem with your code is ch -1
which should be just ch
.
You should do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt){
int[] array = new int[txt.length()];
int i = 0;
char[] ascii1 = txt.toCharArray();
for(char ch:ascii1){
array[i] = ch;
i++;
}
return array;
}
}
Output:
[97, 66, 99]
Alternatively , you can do it as follows:
import java.util.Arrays;
public class ToAscii {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(toAscii("aBc")));
}
static int[] toAscii(String txt) {
int[] array = new int[txt.length()];
char[] ascii1 = txt.toCharArray();
for (int i = 0; i < array.length; i++) {
array[i] = ascii1[i];
}
return array;
}
}
Output:
[97, 66, 99]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.