0

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
  • Do you really need to read these characters one at a time? Commented Sep 27, 2010 at 14:11
  • 2
    From < to >? Aren't you reinventing a XML/HTML parser? Commented Sep 27, 2010 at 14:11
  • @BalusC, I was thinking the same thing... Commented Sep 27, 2010 at 14:13

3 Answers 3

1

Of course. You will need:

  • the method String.charAt(int)
  • the + operator (or the method String.concat, or, if performance matters, the class StringBuilder)
  • the for statement
  • and perhaps an if-statement with a break statement

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

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.
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>.
@BalusC, agreed, the SO can use str.indexOf(endChar, startPos + 1) to find the closest closing bracket. I'm assuming that str = "<foo>"
0

This may not be what you want but it will give you the desired string.

 String desiredString="<Hello>".split("[<>]")[1];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.