Question

Consider this code:

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

What I am looking for is a for-loop that first looks at the character at the current position and then appends it to a string if that character is not ")". However, the char ")" should also be appended to the string. In this example the output should be:

The string result is: (My name is Bob)

Was it helpful?

Solution

Below is a working solution.

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

}
}

OTHER TIPS

Based upon your comment, I believe you dont require to parse the entire string, henceforth I suggest you the following answer

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

Hope this solves your question.

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

}

Try this. Is this what you want to do ? This will prints the substring before ")" as you wrote in comment above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top