如何使用Java中的字符串阅读器获取字符串中的下一个字符



考虑以下代码:

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(

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

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

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

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

希望这能解决你的问题。

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 = "";
        }
    }
}

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

相关内容

  • 没有找到相关文章

最新更新