Hello, I had a string like this:
....... x.y.z.home.room.bed.sheet.type.price
I need to put in an array the last three( sheet, type, price). How can I do, the best chance?
thanks
Printable View
Hello, I had a string like this:
....... x.y.z.home.room.bed.sheet.type.price
I need to put in an array the last three( sheet, type, price). How can I do, the best chance?
thanks
You could use the String's split method to split the string at each '.' and extract the last 3 array elements.
Why not try it and see if it's fast enough before worrying about it.
Sorry, I can't understand that sentence. Are you saying that although it doesn't appear to be slow to you it may not be efficient enough?Quote:
Maybe could be not good even I don't notice that its speed is slow..?
OK see I assume split is the only chance; now: what's the best?
way1 or way2? I would prefer a stack but I'm not able to convert the split string in a stack<String>Code:StringBuilder sb = new StringBuilder();
for (int ii=0; ii < 1000; ii++ ){
sb.append("home" + ".");
}
sb.replace(sb.length()-1, sb.length()-1, "");
String[] sp = sb.toString().split("[.]");
//way 1
for (int i=0; i < sp.length && i<=2; i++)
System.out.println ( sp[sp.length-1-i] );
//way2
List<String> list = new ArrayList<String>( Arrays.asList(sb.toString().split("[.]") ));
for (int q=0; q < 3; q++) {
System.out.println( list.remove( list.size() -1 ) );
}
thanks
No, I didn't say that. There are many ways of doing this but using the split() method is the easiest to code and understand.Quote:
OK see I assume split is the only chance;
The point is you shouldn't be worrying about performance efficiencies until you know there is a problem. And by 'know' I mean having analyzed the code using a profiling tool and not just because you think it might be a problem.
That depends on what you mean by 'Best'. Your code returns the items in reverse order - is that really you want?Quote:
now: what's the best?
Assuming you mean coding style (and you want the items in the correct order) I would do:
Code:StringBuilder sb = new StringBuilder();
for ( int ii = 0; ii < 1000; ii++ ) {
sb.append("home" + ii + ".");
}
sb.setLength(sb.length() - 1);
String[] sp = sb.toString().split("\\.");
for ( int i = sp.length - 3; i < sp.length; i++ ) {
System.out.println(sp[i]);
}