Is there a method or way to read and keep reading chars from a string, putting them in a new string until there is a certain char. Keep reading from < to > but no further. Thankx
3 Answers
Of course. You will need:
- the method
String.charAt(int) - the
+operator (or the methodString.concat, or, if performance matters, the classStringBuilder) - the
forstatement - and perhaps an
if-statement with abreakstatement
The statements and operators are explained in the Java Tutorial, and the method in the api javadoc.
(And no, I will not provide an implementation, since you would learn little by copying it)
Comments
You can actually write a utility that does that
public class StringUtil {
public static String copy(String str, char startChar, char endChar) {
int startPos = str.indexOf(startChar);
int endPos = str.lastIndexOf(endChar);
if (endPos < startPos) {
throw new RuntimeException("endPos < startPos");
}
char[] dest = new char[endPos - startPos + 1];
str.getChars(startPos, endPos, dest, 0);
return new String(dest);
}
};
PS Untested....
Alternatively, you can
String result = str.substring(startPos, endPos + 1); //If you want to include the ">" tag.
3 Comments
Powerlord
You had me up until the
char[] line. That line and the ones afterward seem like an awful lot of work for recreating String.substring.BalusC
And,
lastIndexOf() may not be what you need. This will fail on e.g. text<foo>text</foo>text and return <foo>text</foo> instead of <foo>.Buhake Sindi
@BalusC, agreed, the SO can use
str.indexOf(endChar, startPos + 1) to find the closest closing bracket. I'm assuming that str = "<foo>"
<to>? Aren't you reinventing a XML/HTML parser?