olfek
olfek

Reputation: 3520

Convert String to Character Array? and Retrieve

How do I create a character array from a string? for example, say I have the string "Hello World"

  1. How would I convert it to a character array?
  2. Once converted, how do I retrieve each individual letter one by one?

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

Answers (3)

Hamid Shatu
Hamid Shatu

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

Stephen C
Stephen C

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

scottt
scottt

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

Related Questions