Reputation: 3520
How do I create a character array from a string? for example, say I have the string "Hello World"
My code:
public Character[] toCharacterArray(String s) {
if (s == null) {
return null;
}
Character[] array = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
Now if the above was implemented, how would I retrieve the returned character and how would I output it in an edit text box? using outputBox.setText();
maybe?
Upvotes: 0
Views: 5769
Reputation: 9700
you can convert a String
to Char
array simply using toCharArray()
method...
char[] charArray = string.toCharArray();
So, your updated method should be as follows...
public char[] toCharacterArray(String s) {
char[] array = s.toCharArray();
return array;
}
Upvotes: 3
Reputation: 718798
This appears to be a homework question, so I'm only going to give hints.
1) How would I convert it to a charterer array?
You've already done that!! However:
it would possibly be better if either you used a char[]
instead of a Character[]
, and
if you do continue to use a Character
, then it is better to use Character.valueOf(...)
instead of new Character(...)
.
2) once converted how do I retrieve each and individual letter 1 by 1?
Use a for
loop. It is one of the standard Java statements. Refer to your Java textbook, tutorial, lecture notes ...
... how would i output it in an edit text box... using outputbox.setText(????)
Use static Character.toString(char)
, or Character.toString()
to create a String, depending on the type you have used. You can then pass that as an argument to setText
...
For details of the methods I mentioned above, read the javadocs.
Upvotes: 1
Reputation: 8371
Convert the string to a simple char array like this:
String test = "hello";
char[] chars = test.toCharArray();
Then you can output any particular char in the array like this:
outputbox.setText(String.valueOf(chars[i]);
Upvotes: 1