-2

i try to create a program to encrypt text into code with my own rule. but, i found some problems to split the text and send it to array

i want to see this in Msg array

Msg[0] = "h";
Msg[1] = "e";
Msg[2] = "l";
Msg[3] = "l";
Msg[4] = "o";

and i try to code like this

String text = "hello";
String[] Msg = new String[] {text};

this code works, but the result isn't like i want. can you help me to solve this problem

thanks..

3
  • How is it not working? What you're showing it's doing at the top appears to be what I would expect it to do. What is the result that you would like? Commented Jul 10, 2014 at 23:06
  • possible duplicate of string to string array conversion in java Commented Jul 10, 2014 at 23:08
  • 2
    Do you want to get array of characters? If so you can get char [] via yourString.toCharArray(). Or do you really want to get array of Strings with each character separated? Commented Jul 10, 2014 at 23:08

2 Answers 2

6

If you want to split the string up into each character then use this code:

String text = "hello";
String[] Msg = text.split("(?!^)");

This uses a regular expression to split the code by every spot that is between two characters (excluding the first blank spot).

Here's how it works:

.split(""); would be fine for splitting the string if you're using java 8 as @Pshemo pointed out. But below that you will end up with an array that starts with "" as the first element.

This regular expression avoids that because it uses a negative lookahead (?!) to make sure to not match the beginning of a line, which is represented by the ^ character.

Sign up to request clarification or add additional context in comments.

5 Comments

Any explanation of (!?^)? BTW this regex is no longer needed since Java 8, you can just use split("").
please explain why this would be preferable to simply toCharArray()?
@drewmoore Different return types, this actually does exactly what OP described in example (it returns String[], not char[]).
@drewmoore Because the OP requests that the array be of String.
indeed he does. i'm sorry, i misread the question..
4

char[] String.toCharArray() is probably what you are looking for.

See: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()

2 Comments

The desired output indicates that Msg is a string[] and not a char[]. Why would someone do that, I don't know, but I'm afraid this does not answer the question.
Sometimes the asker doesn't really know what they want. Hence the "is probably what you are looking for". @BitNinja's answer above is the solution if the OP's question was exactly what he was asking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.