Hi,
I have a string like this
heads tails heads tails 10 5
How can I get the 10 and the 5 into seperate variables
e.g.
headCount=10
tailsCount=5
I need to get all the integers out of a String
is it possible?
Printable View
Hi,
I have a string like this
heads tails heads tails 10 5
How can I get the 10 and the 5 into seperate variables
e.g.
headCount=10
tailsCount=5
I need to get all the integers out of a String
is it possible?
yes, use regular expressions.
take a look at String.matches() in java doc
I found it but I don't really understand regular Expressions, can anyone give me an example?
examples? not me, its a whole chapter by itself.
if only christ was here...
try googleing for it. java regex
here's one:
Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)
Code:String one="10";
int two=Integer.parseInt(one);
err no. its more like:
String s = "heads tails heads tails 10 5";
and he wants to extract 10 and 5 out of it.
Figured out a way to do it
String s="heads tails heads tails 10 5";
String[] arraystring=s.split(" ");
int anint = String[4]; //which will be 10
int anotherint=String[5]; //which will be 5
OH its a fixed string. i thought you have a dynamic string.
Code:
public class Numbers {
/**
* @param args
*/
public int[] hasNumber(String s) {
int[] numbs=new int[s.length()];
int count=0;
for (int j = 0;j < s.length();j++) {
if (Character.isDigit(s.charAt(j))){
numbs[count]=Integer.parseInt(Character.toString(s.charAt(j)));
for(int i=j+1;Character.isDigit(s.charAt(i));i++){
j=i;
numbs[count]=numbs[count]*10+Integer.parseInt(Character.toString(s.charAt(j)));
}
count++;
}
}
return numbs;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Numbers().hasNumber("123fdgdf78hj");
}
}
thats a good idea to avoid regex.
actually the string must end w/ a non-digit, otherwise, it'll throw an exception.
Here's a way to use a regex to get rid of text. You would then split, as you did, and not have to worry about the position. Given that you are dealing with fixed position, this is unnecessary, but learning regex will save you in a lot of situations.
String workString = s.replaceAll("[^\\d ]", "");
workString = workString.replaceAll("(^ +| +$"), "");
The first expression removes everything but digits and blanks. Note the the \\d has two backslashes because Java uses backslash as an escape character, the regex only sees \d.
The second expression removes leading and training spaces.
Go to a regex tutorial site and find out what all that mess does. It's a good way to start.