Java-How can I peel off a single char in a String and store them in a 1D array?
I have a String "301918574X"
and I want to store each letter i开发者_如何学Gonto an array with 3
in the first slot, 0
in the second slot, 1
in the third slot, etc.
How would I go about doing this?
EDIT:
I now have each character assigned to the appropriate array slot. But there is one letter in the array, and that's "X"
(this is actually an ISBN). When there is an X
, it should have the value of 10
but obviously that won't work in a character array.
char[] theArrayYouWant = str.toCharArray();
You are searching for String.toCharArray()
. As the documentation states, "it returns a newly allocated character array whose length is the length of the string and whose contents are initialized to contain the character sequence represented by the string."
The API documentation for the platform should be the first resource to look at when wondering if a class directly supports a specific operation.
String testString="301918574X";
char[] resultArray = new char[12];
for (int i=0;i<testString.length();i++)
{
resultArray[i] = testString.charAt(i);
}
If you just need indexed access, you can use String.charAt()
. If you really need the array, use String.toCharArray()
.
To "do Math with" your characters, store them not as char
, but as int
.
Here is an example:
int[] digits = new int[str.length()];
for(int i : 0; i < str.length -1; i++) {
digits[i] = Character.digit(str.charAt(i), 10);
}
char last = str.charAt(str.length()-1);
if(last == 'X')
digit[digits.length-1] = 10;
else
digit[digits.length-1] = Character.digit(last, 10);
(In ISBNs only the last digit can be an X.)
精彩评论