Converting a string of characters to an int array in Java - java

I'm wondering how I can convert a string like of letters to their numerical value in an array. For example, A is 0, B is 1. I know I need to use like a for loop like this:
for (int i = 0; i < 26; i++), but I'm not sure what code fragment to actually use to do the converting into an int array? Help?

Converting a letter (char) to an integer representing its place in the alphabet is easier than some people realize; all you have to do is:
(int)(c - 'A') // the "distance" between c and 'A' = place of c in alphabet
Loop through the characters of your string and perform this operation for each, storing the results in a new int array.

You can get the each Char by yourString.charAt(i) and then cast it with (int) this will gave you the Corresponding ASCII then subtract from the ASCII of 'A'. You will have what you want
result = (int)yourString.charAt(i) - (int)'A'

Related

Getting ints array instead of characters array

I am trying a code problem to convert double to string and then insert that to an array. I tried various methods but these don't give expected output.
public int[] makePi() {
double PI = Math.PI;
String sPI = String.valueOf(PI);
int[] Arr = new int[3];
for(int i =0; i<3; i++)
{
Arr[i] = sPI.charAt(i);
}
return Arr;
}
Output should be an array with first three characters of PI as below :-
[ 3, 1, 4 ] while I am getting [51, 46, 49]
I will handle decimal character if needed.
Just a hint is needed.
Please don't provide full program that will be a spoiler. :-)
Look at the ASCII table. Do you see what are the corresponding chars for the integers you're getting? This should be a good hint for you.
Note that you're assigning the result to an int array, while you're running on characters.
you're storing chars into an int array. hence theie respective ascii values will be stored in array (you're effectively converting char to int)
3 (char) -> 51 (ASCII Value)
. (char) -> 46 (ASCII Value)
1 (char) -> 49 (ASCII Value)
your array length is 3, so only first 3 chars are converted to ascii which is 3.1, not 3.14
But now if you want to store it into an char array (which i feel you're trying to do), all you need is -
char[] charArray = sPI.toCharArray();
Plus, I dont think you want to store in int array as though you can convert ascii values int their respective int value, but what about '.' which is not a valid int.
What you get in your array are values of characters (so something like 70 for '3', I neither remember nor want to remember exact values). You must convert value of character into the number itself. Hint: characters are numbered in the following way:
'0' - n
'1' - n + 1
'2' - n + 2
and so on.
If you want to extract the numeric values of the digits, I would advise against doing explicit comparisons and arithmetic on the character values.
The Character class provides helper methods, which are less error-prone and more readable:
int outIndex = 0;
for (int i = 0; i < 3 /* && i < sPI.length() */; ++i) {
char c = sPI.charAt(i);
if (Character.isDigit(c)) {
Arr[outIndex++] = Character.getNumericValue(c);
}
}
/* assert outIndex == 3 */
return Arr;
I've commented out some code which I'd put in there for more robustness - it's not strictly necessary in this case, since we know that sPI has at least 3 digits in it. (Mind you, if we're going to hard-code that assumption, we may as well simply return new int[] { 3, 1, 4 };).

Why do we write A.charAt(i) but not A.charAt[i]? And why do we write " - 'A' "?

public static int get(String A) // it is a method
{
int count = 1;
for (int i = 0; i < A.length(); i++) // So A reads line (any word, for example "Car"), so I understand that length will be 3 and that java will check all the characters.
{
int num = (A.charAt(i) - 'A') + 1;
count *= num;
}
return count;
}
You write A.charAt(i) because charAt is a function, not an array.
You write A.charAt(i) - 'A' to compute the difference between A's i:th character and the character 'A'.
The class String is an immutable or value object. It doesn't give you direct access to the characters which make up the string, mainly for performance reasons but also since it helps to avoid a whole class of bugs.
That's why you can't use the array access via []. You could call A.getChars() but that would create a copy of the underlying character array.
char is the code for a character. 'A' == 65, for example. See this table. If A.charAt(1) returns 'F' (or 70), then 'F' - 'A' gives you 5. +1 gives 6.
So the code above turns letters into a number. A pattern which you'll see pretty often is charAt(i) - '0' to turn a string into a number.
But the code above is odd in this respect since count *= num produces a pretty random result for the input. To turn the letters into numbers, base 26, it should read count = count * 26 + num.
A.charAt(i) is a method for strings, you could also do A[i] to access the same position directly.
When you do an operation (+ or -) with chars, you get an int.
Java API for charAt() function
charAt() is a java method, not an Array
returns the char value at the specified index.
Syntax:
Here is the syntax of this method:
public char charAt(int index);
Because charAt() is a method that returns a character from a given String, and not an array. Characters are written 'A'. Strings are written "A".
Because charAt is a method within string and it accepts index. String internally maintains char array and it's all hidden from us and hence you have a method not the array itself.
Reason for -'A' is user wants to convert that character to integer. So for e.g. You character is 'B', User wants to convert it into int using ascii value of 'B' which is 66 - ascii value of 'A' which 65
num = 66 - 65 + 1
And do further processing.
because charAt() is a method in java for string it and it returns a character. and 'A' refers to a char type while we write "A" for string type
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29

Convert XSLT function (string-to-codepoints) to Java

How can I "translate" this XSLT code to Java ?
<xsl:value-of select="number(string-to-codepoints(upper-case($char)) - string-to-codepoints('A'))+10"/>
I only know that: "The fn:string-to-codepoints function returns a sequence of xs:integer values representing the Unicode code points."
From the example that is given in (http://www.xsltfunctions.com/xsl/fn_string-to-codepoints.html) :
string-to-codepoints('a') = 97
I found this:
char ch = 'a';
System.out.println(String.format("\\u%04x", (int) ch));
But I get : \u0061
For a single char you can just cast it to int to get the decimal value:
System.out.println((int)ch);
For a String there's .toCharArray() to convert it to a char[] but that isn't quite the same as a "sequence of codepoints" if the String involves Unicode characters outside the BMP (i.e. above U+FFFF), which are represented in Java as a surrogate pair of two char values. To handle surrogates properly you would need to use a technique like the one described in this answer.
To answer the specific question you ask, you can do
number(string-to-codepoints(upper-case($char)) - string-to-codepoints('A'))+10
in Java as
char ch = // wherever you get $char from
int num = Character.toUpperCase(ch) - 'A' + 10;
since char is an integer type in Java and you can add or subtract char values like any other number.
But this will probably only give you a sensible answer when the initial ch is an ASCII letter.
You print the value as unicode escape sequence; XSLT prints a decimal value.
This should work much better:
System.out.println("a".codePointAt(0));

How do I convert a integer representing a character to a string?

I am reading a file in Java, which gives me each character as an integer, and then processing each character one at a time. However, I cannot compare that character when it is in integer form, so how can I convert it?
Example:
I want: 93 → A
NOT: 5 → 5
Then, I can compare it with an "if" statement.
Character.toString((char)93);
Use Integer.parseInt() if you are starting with a string containing the characters 9 and 3.
The following should work"
int i = 93;
char c = (char)i;
Basically you typecast the int to its equivalent character.
Just cast like int i = read(); char aChar = (char)i; when appending stringBuilder.append((char)i); or string += (char)i;

BigInteger to String according to ASCII

Is there a way to convert a series of integers to a String according to the ASCII table. I want to take the ASCII value of a String and convert it back to a String. For example,
97098097=> "aba"
I really need an effective way of taking an integer and converting it to a String according to its ASCII value. This method must also take into account the fact that there is no zero in front of the '9' when the String "aba" has an ASCII value of 97098097 as 'a' has an ASCII value of 097 and a String "dee" has one of 100101101. This means that not every number will have an ASCII value that has a number of digits that is a multiple of three.
If you have any misunderstandings of what I'm trying to do please let me know.
No lookup table required.
while (string.length() % 3 != 0)
{
string = '0' + string;
}
String result = "";
for (int i = 0; i < string.length(); i += 3)
{
result += (char)(Integer.parseInt(string.substring(i, i + 3)));
}
First, I would create some sort of lookup table in your code with all the ascii values and their String equivalent. Then take the big int and convert it to a String. Then do the mod of 3 with the length of your bigint string to determine if you need to add 1, 2, or no 0's to the front of it. Then just grab every 3 integers from the front of the number, compare it to the lookup table, and append the corresponding value to your result string.
Example:
Given 97098097
You would convert it to: "97098097"
Then you do a mod with 3 resulting in a value of 1, so 1 zero needs to be added.
Append 1 zero: "097098097"
Then grab every 3 from the front and compare to look up table:
097 -> a, so result += "a"
098 -> b, so result += "b"
097 -> a, so result += "a"
You end with result being "aba"

Categories