Java string help

Talk about your favorite PC games, Steam and building awesome custom rigs!

Moderator: Moderators

Post Reply
Edutainment
Posts: 423
Joined: Tue Feb 20, 2007 8:33 pm
Location: Ontario, Canada

Java string help

Post by Edutainment »

Haven't been here in a while. I'm starting to learn Java at school and need a little help.

How do I put the characters of a string into an array?

public class Draw(String s){
//turn s into array here
}

Plz & thanks :D
SpongeBuell
Senior Member
Posts: 5190
Joined: Wed Apr 07, 2004 10:52 am
Location: Colorado
Contact:

Post by SpongeBuell »

first of all, you'd want a method... the public class Draw(String s){ line is a mix of what you'd have for a method and a class rolled into one. Java actually has a method built in to do just that, anyway. s.toCharArray() would do the trick, assuming s is your string name. If you need to do this in the middle of code, just do this:

Code: Select all

char[] charArray = new char[s.length()]; //s.length gives the exact number of fields in the string.  Any number can be used.
charArray = s.toCharArray();
Life of Brian wrote:
RYW wrote:RYW:

Rare
Yellow
Weasel
I'll be honest with you - I would have never guessed that.
Edutainment
Posts: 423
Joined: Tue Feb 20, 2007 8:33 pm
Location: Ontario, Canada

Post by Edutainment »

My teacher told me you can handle strings just like arrays, and you don't need to convert it, at least not for my uses. How would I refer to a specific character? Same as an array? I'm a nub.
soundwave
Senior Member
Posts: 3653
Joined: Wed Feb 23, 2005 1:51 pm
Location: Connecticut

Post by soundwave »

You'd use the charAt(int index) method.

Code: Select all

String s = "hello"
s.charAt(1); // should =='e'
I guess with that method its technically acting like an array, they both have indeces, still that's a weird comparison.
Post Reply