【问题标题】:How can I get the next char in my string with the stringreader in Java?如何使用 Java 中的 stringreader 获取字符串中的下一个字符?
【发布时间】:2013-01-14 16:22:20
【问题描述】:

考虑这段代码:

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

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

【问题讨论】:

  • 我没问你问题。你想要的是第一个括号之间的子字符串吗?
  • 我想查看字符串名称中的每个字符并返回“)”之前的字符串部分。然而,字符“)”也应该在该字符串中。

标签: java string char stringreader


【解决方案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();
}

}
}

【讨论】:

  • 我已经按照你想要的方式做了,虽然它有一些性能问题。例如,您可以使用 StringBuffer,而不是使用 String 作为结果。
  • 您确定这部分:'for (;c!= ')';) {' 有效吗?我认为您必须使用 ascii 代码而不是 ')'
【解决方案2】:

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

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

希望这能解决您的问题。

【讨论】:

    【解决方案3】:
    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 = "";
            }
        }
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多