Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting String Vector Elements??

 
rikstar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I cast a string which is the first Vector element into a char type? i.e I have a Vector which holds strings, and I need to retrieve it inorder to print onto the screen. BUT I need to print the each character individually, which means I have to cast the "string" into type "char" BUT HOW? So far I have this..
System.out.println(sentence.firstElement());
I need a solution ASAP
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe there is s toCharArray method that you can use. I would personally loop through the string printing out each element of the string. Also check out tghe charAt method.

Bosun
 
BJ Grau
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Bosun - I would do something like this:
Vector v = new Vector();
v.addElement("One");
v.addElement("");
v.addElement("Two");
v.addElement("Three");
Enumeration e = v.elements();
while(e.hasMoreElements()) {
String s = (String) e.nextElement();
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
System.out.println(c);
}
}
 
Jason Ford
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you need to print each character individually? Is it a requirement of your program? If not, you should just print out the entire string at once; your code will be easier to read and maintain.
Jason
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic