如何使用Java中的stringreader获取字符串中的下一个char?

时间:2013-01-14 16:22:20

标签: java string char stringreader

考虑以下代码:

public static void main (String[] args) {

    String name = "(My name is Bob)(I like computers)"

    StringReader s = new StringReader(name);

    try {
        // This is the for loop that I don't know 
        for () {
            String result = "";  
            // Here the char has to be appended to the String result.
        }
        System.out.println("The string is: " + result);

    } catch (Exception e) {
        e.toString();
    }
}

我正在寻找的是一个for循环,首先查看当前位置的字符,然后如果该字符不是“)”则将其附加到字符串。但是,char“)”也应该附加到字符串。在此示例中,输出应为:

字符串结果是:(我的名字是鲍勃)

3 个答案:

答案 0 :(得分:1)

以下是一个有效的解决方案。

import java.io.StringReader;

public class Re {
public static void main (String[] args) {
String name = "(My name is Bob)(I like computers)";

StringReader s = new StringReader(name);

try {
    // This is the for loop that I don't know
    String result = "";
    int c = s.read();
    for (;c!= ')';) {
        result = result + (char)c;
        // Here the char has to be appended to the String result.
        c = s.read();
    }
    result = result + ')';
    System.out.println("The string is: " + result);

} catch (Exception e) {
    e.toString();
}

}
}

答案 1 :(得分:1)

根据您的评论,我相信您不需要解析整个字符串,因此我建议您回答以下问题

    String name = "(My name is Bob(I like computers";
    int firstCloseBracket = name.indexOf(")");
    String result=null;
    if(-1!=firstCloseBracket){
        result = name.substring(0,firstCloseBracket+1);
    }

    System.out.println(result);

希望这能解决你的问题。

答案 2 :(得分:0)

public static void main(String[] args) {
    String name = "(My name is Bob)(I like computers)";
    String result = "";
    for (int i = 0; i < name.length(); i++) {
        result = result + name.charAt(i);
        if (name.charAt(i) == ')') {
            System.out.println(result);
            result = "";
        }
    }

}

试试这个。这是你想要做的吗? 这将在“)”之前打印子字符串,正如您在上面的评论中所写的那样。