在分隔符之间反转多个字符串

时间:2016-01-05 18:42:32

标签: java reverse

我需要替换分隔符的字符串中的子字符串。例如(abc),(def)应该是(cba),(反馈)后的(进给)。

我尝试了以下代码,但它没有反转就返回了字符串。

String s = "(abc),(cdef)";
s =   s.replaceAll("\\(\\[.*?\\]\\)", 
             new StringBuilder("$1").reverse().toString());

4 个答案:

答案 0 :(得分:1)

替代方案:

String s = "(abc),(cdef),(ghij)", res = "";
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(s);
while(m.find()){
    res += "(" + new StringBuilder(m.group(1)).reverse().toString() + "),";
}
if(res.length() > 0)
    res = res.substring(0,res.length()-1);
System.out.println(res);

打印:

(cba),(fedc),(jihg)

答案 1 :(得分:1)

如果您使用的是Java 8的另一种选择:

String s = "(abc),(cdef),(ghijklm)";
Pattern pattern = Pattern.compile("[a-z]+");
Matcher matcher = pattern.matcher(s);
List<String> reversedStrings = new ArrayList<>();

while(matcher.find()){
     reversedStrings.add(new StringBuilder(matcher.group()).reverse().toString());
}
reversedStrings.forEach(System.out::print);

答案 2 :(得分:1)

使用堆栈反转的低技术方法:

public static String reverse(String s) {
    StringBuilder buffer = new StringBuilder();
    Stack<Character> stack = new Stack<>();

    for(char c : s.toCharArray() ) {
        if(Character.isLetter(c)) { stack.push(c); }
        else if(c == ')') {
            while (!stack.isEmpty()) { buffer.append(stack.pop()); }
            buffer.append(',');
        }
    }
    return buffer.deleteCharAt(buffer.length()-1).toString();
}

答案 3 :(得分:0)

对于另一种观点,这里有一个算法,用于执行括号的就地修剪和StringBuilder上每个分量的内部反转。我省略了输入验证检查,转而关注核心算法。如果您将其用于实际,则可能需要添加更多输入验证。例如,它当前在空输入字符串或字符串上抛出异常,该字符串意外地在末尾有一个尾随',',后面跟着另一个字符串组件。

public class TestReverse {
    public static void main(String[] args) {
        for (String arg: args) {
            StringBuilder input = new StringBuilder(arg);

            // Point start at first '(' and end at first ','.
            int start = 0, end = input.indexOf(",");

            // Keep iterating over string components as long as we find another ','.
            while (end > 0) {
                // Trim leading '(' and readjust end to keep it pointing at ','.
                input.deleteCharAt(start);
                end -= 1;

                // Trim trailing ')' and readjust end again to keep it pointing at ','.
                input.deleteCharAt(end - 1);
                end -= 1;

                // Reverse the remaining range of the component.
                reverseStringBuilderRange(input, start, end - 1);

                // Point start at next '(' and end at next ',', or -1 if no ',' remaining.
                start = end + 1;
                end = input.indexOf(",", start);
            }

            // Handle the last string component, which won't have a trailing ','.
            input.deleteCharAt(start);
            input.deleteCharAt(input.length() - 1);
            reverseStringBuilderRange(input, start, input.length() - 1);
            System.out.println(input);
        }
    }

    private static void reverseStringBuilderRange(StringBuilder sb, int start, int end) {
        for (int i = start, j = end; i < j; ++i, --j) {
            char temp = sb.charAt(i);
            sb.setCharAt(i, sb.charAt(j));
            sb.setCharAt(j, temp);
        }
    }
}

> javac TestReverse.java && java TestReverse '(abc),(def)' '(foo),(bar),(baz)' '(just one)'
cba,fed
oof,rab,zab
eno tsuj