1

考虑这段代码:

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 循环,它首先查看当前位置的字符,然后如果该字符不是“)”,则将其附加到字符串中。但是,字符“)”也应该附加到字符串中。在此示例中,输出应为:

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

4

3 回答 3

0

下面是一个可行的解决方案。

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();
}

}
}
于 2013-01-14T16:28:45.363 回答
0

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

    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);

希望这能解决你的问题。

于 2013-01-14T16:33:52.350 回答
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 = "";
        }
    }

}

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

于 2013-01-14T17:14:42.547 回答