문제

I've been trying to figure out how to implement a problem (linked further down) but, I'm hitting a wall.

Basically I have to reformat source code that uses next line curly braces to end of line curly braces. For some reason, the professor for my class decided to assign this problem in our Strings chapter and not in the Text I/O chapter (which is about 5 chapters later).

String sourceString = new String(Files.readAllBytes(Paths.get("Test.txt")));
String formatted = sourceString.replaceAll("\\s\\{", "\\{");
System.out.println(formatted);

So that's what I have so far. When I do a run, the output is the same as the source file. I followed this problem and using an idiom I found to convert all of the file into a String, the replaceAll method stopped... replacing.

While I still had it set up like this

StringBuilder source = new StringBuilder();
    while(s.hasNext()){
        source.append(s.nextLine());
    }
    String sourceString = source.toString();
    String formatted = sourceString.replaceAll("\\)\\s*\\{", ") {");
    System.out.println(formatted);

the output is all on a single line. I feel like the replaceAll method isn't occurring at all. I feel like I'm forgetting something blatantly obvious.

도움이 되었습니까?

해결책

The second argument of replaceAll() is a String, not a regex, so no need to escape the { there.

Also add a + to denote one or more whitespaces.

So:

sourceString.replaceAll("\\s+\\{", "{")

다른 팁

If you want to do it without using replaceAll() and regex then try this one:

    String nextLine = null;
    String currentLine = null;
    while (s.hasNext()) {
        currentLine = s.nextLine();
        if (currentLine.trim().endsWith(")")) {
            while(s.hasNext()){
                if((nextLine = s.nextLine()).trim().length() != 0){
                    break;
                }
            }

            if (nextLine.trim().equals("{")) {
                source.append(currentLine).append(" {").append("\n");
            } else {
                source.append(currentLine).append("\n");
            }

        } else {
            source.append(currentLine).append("\n");
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top