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ループです。ただし、文字「)」も文字列に追加する必要があります。この例では、出力は次のようになります。

文字列の結果は次のとおりです:(私の名前はボブです)

4

3 に答える 3

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 に答える
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 に答える