Strip Comments

kata programming

مساله:

راه حل را به گونه ای تکمیل کنید که تمام متنی را که بعد از مجموعه ای از نشانگرها که از ورودی گرفته می شود، حذف کند. هرگونه فضای خالی در انتهای خط نیز باید حذف شود.

مثال:

رشته ورودی به صورت زیر است:

apples, pears # and bananas
grapes
bananas !apples

خروجی باید به صورت زیر باشد:

apples, pears
grapes
bananas

کدی که فراخوانی می شود به صورت زیر است:

var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"

Description:

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.

Example:

Given an input string of:

apples, pears # and bananas
grapes
bananas !apples

The output expected would be:

apples, pears
grapes
bananas

The code would be called like so:

var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"

import java.util.Arrays;
import java.util.stream.Collectors;

public class StripComments {

  public static String stripComments(String text, String[] commentSymbols) {
    String pattern = String.format(
        "[ ]*([%s].*)?$",
        Arrays.stream( commentSymbols ).collect( Collectors.joining() )
    );
    return Arrays.stream( text.split( "\n" ) )
        .map( x -> x.replaceAll( pattern, "" ) )
        .collect( Collectors.joining( "\n" ) );
  }

}
import java.util.Arrays;
import java.util.stream.Collectors;

public class StripComments {
    public static String stripComments(String text, String[] symbols) {
        return Arrays.stream(text.split("\n")).map(s -> {
            for (String symbol : symbols) s = s.replaceAll("(\\s+$)|(\\s*[" + symbol + "].*)", "");
            return s;
        }).collect(Collectors.joining("\n"));
    }
}
public class StripComments {

  public static String stripComments(String text, String[] commentSymbols) {
    return text.replaceAll("(?m)\\h*([" + String.join("",commentSymbols) + "].*)?$", "");
  }
  
}
import static java.lang.String.format;
import static java.lang.String.join;

public class StripComments {

    public static String stripComments(String t, String[] cS) {
        return t.replaceAll(format("[%s][^\\n]*", join("", cS)), "")
                .replaceAll("[ \t]+\n", "\n").replaceAll("[ \t]+$", "");
    }
}
public class StripComments {

  public static String stripComments(String text, String[] commentSymbols) {
    return text.replaceAll(" *([" + String.join("", commentSymbols) + "].*)?(\n|$)", "$2");
  }
  
}

دیدگاهتان را بنویسید