What does String.substring exactly do in Java? - Stack Overflow
How to correctly use the substring method? (Java)
string - Substring search in Java - Stack Overflow
Java: Getting a substring from a string starting after a particular character - Stack Overflow
It's supposed to be an efficiency measure. i.e. when you're taking a substring you won't create a new char array, but merely create a window onto the existing char array.
Is this worthwhile ? Maybe. The downside is that it causes some confusion (e.g. see this SO question), plus each String object needs to carry the offset info into the array, even if it's not used.
EDIT: This behaviour has now changed as of Java 7. See the linked answer for more info
Turning it around, why allocate a new char[] when it is not necessary? This is a valid implementation since String is immutable. It saves allocations and memory in the aggregate.
Hey guys, I've been working on this Java homework for my class and this whole section about string manipulation is confusing me.
The homework asks to add statements that use the substring method to get the first half and second half of phrase.
I'm assuming that means using the substring method, but I always get errors trying to compile what I put in. So here's the code. I'm not exactly sure how to use the substring method in the way they ask, and my book doesn't really go over it well. Should I be creating another variable or just use what I have?
I'm assuming the problems you're having with indexOf() related to you using the character version (otherwise why would you be searching for w when looking for world?). If so, indexOf() can take a string argument to search for:
String s = "hello world i am from heaven";
if (s.indexOf("world") != -1) {
// it contains world
}
as for log base 2, that's easy:
public static double log2(double d) {
return Math.log(d) / Math.log(2.0d);
}
For an exact String comparison, you can simply do:
boolean match = stringA.equals(stringB);
If you want to check that a string contains a substring, you can do:
boolean contains = string.contains(substring);
For more String methods, see the javadocs
String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));
A very simple implementation with String.split():
String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];