We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I want to write a function which take strings as input and returns an array of characters consisting of the characters in the order they originally appear in the string. For example, explode( "Dirk" ) should return the array {'D', 'i', 'r', 'k'}. However, I cannot get it to work.
char[] explode(String s) {
String theString = s;
char[] c = new char[theString.length()];
for (int i = 0; i < theString.length(); i++) {
c[i] = theString.charAt(i);
return c[i];
}
}
I also want to write a function that behaves like the above one in reverse. Taking an array of characters as input and returns a String consisting of all the characters in the array glued together. For example, returning ("Dirk") after inputting the array {'D', 'i', 'r', 'k'}.
Answers
https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text
http://docs.Oracle.com/javase/8/docs/api/java/lang/String.html#toCharArray--
https://forum.Processing.org/two/discussions/tagged?Tag=tochararray()
Your line with return must be outside the for loop, after
}
and
return c;
EDITED
The second part is simple-
@Nekios -- The easiest way is to use toCharArray, as @GoToLoop suggests. This example sketch gives two examples, running on a String variable or directly on a String in-place:
For more discussion, see:
Addendum -- you asked about the reverse case. It is extremely simple -- just use the String constructor:
HOWEVER, see this discussion...
...and in particular:
In general, don't bother with all this converting and reconverting back. Your String is already a charArray in effect, and individual chars can be accessed (or looped through) at any time.