Java Question

  • Java
  • Thread starter NiaSphinx
  • Start date
  • #1
4
0
Hi guys,

I was wondering if anyone could explain to me/point me in the right direction on how to manipulate a String read in from the user in a particular way. I'm trying to read in a String, and then I want to sort of split the string up into ints and chars and associate them to variables.
For instance:
If I have a string: 6G2N42B, is there a way to access the ints '6', '2', '42' and a way to access the chars 'G', 'N' and 'B' ?

Thanks
 

Answers and Replies

  • #2
daniel_i_l
Gold Member
867
0
You can use the Scanner class:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
For example, the output of
import java.util.Scanner;
public class Hello
{
public static void main(String[] argv)
{
String s = "a 123 b";
Scanner scan = new Scanner(s);
System.out.println(scan.next());
System.out.println(scan.next());
System.out.println(scan.next());
}
}
is:
a
123
b
 
  • #3
Borg
Science Advisor
Gold Member
1,936
2,691
This will work without having to put empty spaces in your input string:

String inputString = "6G2N42B";
String expression = "(\\d*+)"; // Searches for all groups of numbers
Pattern myPattern = Pattern.compile(expression);
Matcher matcher = myPattern.matcher(inputString);
while(matcher.find()){
if(!matcher.group().equalsIgnoreCase("")){
System.out.println("matcher.group(): " + matcher.group());
}
}

expression = "(\\D*+)"; // Searches for all groups of non-numbers
myPattern = Pattern.compile(expression);
matcher = myPattern.matcher(inputString);

while (matcher.find()) {
if(!matcher.group().equalsIgnoreCase("")){
System.out.println("matcher.group(): " + matcher.group());
}
}

Output:


matcher.group(): 6
matcher.group(): 2
matcher.group(): 42
matcher.group(): G
matcher.group(): N
matcher.group(): B
 
  • #4
4
0
Thanks, I'll give that a try :)
 

Related Threads on Java Question

  • Last Post
Replies
5
Views
4K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
4
Views
1K
Replies
11
Views
2K
Replies
2
Views
1K
Replies
6
Views
737
  • Last Post
2
Replies
28
Views
2K
Top