开发者

Front-popping a Java String

Having read the documentation of Java's String class, it doesn't appear to support popping from front(which does make sense since it's basically a char array). Is there an easy way to do something like

String firstLetter = someString.popFro开发者_如何学Cnt();

which would remove the first character from the string and return it?


A String in Java is immutable, so you can't "remove" characters from it.

You can use substring to get parts of the String.

String firstLetter = someString.substring(0, 1);
someString = someString.substring(1);


You can easily implement this by using java.lang.StringBuilder's charAt() and deleteCharAt() methods. StringBuilder also implements a toString() method.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html


I don't think there is something like that (even because strings can't be changed - a new one needs to be created), but You can use charAt and subString to implement your own.

An example of charAt:

String aString = "is this your homework Larry?"; 
char aChar = aString.charAt(0);

Then subString:

String anotherString = aString.substring(1, aString.length());


So you basically want to have the String in a FIFO stack? For that you can use a LinkedList which offers under each a pop() method to pop the first from the stack.

To get all characters of a String in a LinkedList, do so:

String string = "Hello World";
LinkedList<Character> chars = new LinkedList<Character>();
for (int i = 0; i < string.length(); i++) chars.add(string.charAt(i));

Then you can pop it as follows:

char c = chars.pop();
// ...

Update: I didn't see the comment that you'd like to be able to get the remaining characters back as a string. Well, your best bet is to create and implement your own StringStack or so. Here's a kickoff example:

public class StringStack {
    private String string;
    private int i;

    public StringStack(String string) {
        this.string = string;
    }

    public char pop() {
        if (i >= string.length()) throw new IllegalStateException("Stack is empty");
        return string.charAt(i++);
    }

    public String toString() {
        if (i >= string.length()) throw new IllegalStateException("Stack is empty");
        return string.substring(i, string.length());
    }
}

You can use it as follows:

String string = "Hello World";
StringStack stack = new StringStack(string);
char c = stack.pop();
String remnant = stack.toString();
// ...

To make it more solid, you can eventually compose a LinkedList.


You should look at a StringReader. The read() method returns a single character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜