Java:如何根据非字母分隔符反转字符串?

huangapple go评论70阅读模式
英文:

Java: How to reverse string based on non alphabetic delimiters?

问题

String fileContent = "Joe'); MAKE TEST random;--";
String[] splitWords = fileContent.split("[^a-zA-Z0-9']+");

StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
    int idx = fileContent.indexOf(word, stringBuilder.length());
    String delim = fileContent.substring(stringBuilder.length(), idx);
    stringBuilder.append(delim);

    StringBuilder output = new StringBuilder(word).reverse();
    stringBuilder.append(output);
}
return stringBuilder.toString();

Current output: 'eoJ); EKAM TSET modnar

Desired output: eoJ'); EKAM TSET modnar;--


<details>
<summary>英文:</summary>

How to reverse string based on non alphabetic delimiters? I suspect my regex may be the problem. 

String fileContent = "Joe'); MAKE TEST random;--";
String[] splitWords = fileContent.split("[^a-zA-Z0-9']+");

StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
int idx = fileContent.indexOf(word, stringBuilder.length());
String delim = fileContent.substring(stringBuilder.length(), idx);
stringBuilder.append(delim);

StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);

}
return stringBuilder.toString();


Current output: `&#39;eoJ); EKAM TSET modnar`

Desired output: `eoJ&#39;); EKAM TSET modnar;--`


</details>


# 答案1
**得分**: 2

你不需要正则表达式来实现这个。看起来你想要翻转仅为字母或数字的字符。然后你可以按照以下方式操作 - 获取字符数组中找到的字符是字母或数字的起始和结束索引,然后原地翻转。然后返回一个新的字符串,其中字符被原地翻转。

```java
private static void reverseWords(char[] c) {
    int start = 0, end = c.length;
    while (start < end) {
        int pre = start;
        while (start < c.length && Character.isLetterOrDigit(c[start]))
            start++;
        if (pre < start)
            reverseWord(c, pre, start - 1);
        start++;
    }
}

private static void reverseWord(char[] c, int start, int end) {
    while (start < end) {
        char temp = c[start];
        c[start] = c[end];
        c[end] = temp;
        start++;
        end--;
    }
}

你可以在这里测试这段代码。

英文:

You don't need a regex for this. It seems you want to reverse characters that are only alphabets or digits.
Then you could do this way - get the start and end indices of the character array where you find the character to be a letter or digit and then reverse in place. Then return a new String with the characters reversed in place.

private static void reverseWords(char[] c) {
    int start = 0, end = c.length;
    while ( start &lt; end ) {
      int pre = start;
      while ( start &lt; c.length &amp;&amp; Character.isLetterOrDigit(c[start]) ) 
        start++;
      if ( pre &lt; start ) 
         reverseWord(c, pre, start-1);
      start++;  
    }
  }

  private static void reverseWord(char[] c, int start, int end) {
    while ( start &lt; end ) {
      char temp = c[start];
      c[start] = c[end];
       c[end]  = temp;
      start++;
      end--;
    }
  }

You can test this code here

答案2

得分: 1

以下是翻译好的内容:

您可以匹配和反转仅包含1个或更多字母的块使用简单的`\p{L}+`模式),并保留其余部分不变

String s = "Joe&#39;); MAKE TEST random;--";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\p{L}+").matcher(s);
while (m.find()) {
    String replacement = new StringBuilder(m.group()).reverse().toString();
    m.appendReplacement(result, replacement);
}
m.appendTail(result);
System.out.println(result.toString()); // => eoJ&#39;); EKAM TSET modnar;--

请参阅在线Java演示

英文:

You may match and reverse only chunks of 1+ letters (with a simple \p{L}+ pattern) and keep the rest as is:

String s = &quot;Joe&#39;); MAKE TEST random;--&quot;;
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile(&quot;\\p{L}+&quot;).matcher(s);
while (m.find()) {
	String replacement = new StringBuilder(m.group()).reverse().toString();
    m.appendReplacement(result, replacement);
}
m.appendTail(result);
System.out.println(result.toString()); // =&gt; eoJ&#39;); EKAM TSET modnar;--

See the Java demo online.

答案3

得分: 1

你的代码在两处做了修改:

  1. 替换模式
  2. 检测尾部分隔符
String fileContent = "Joe'); MAKE TEST random;--";
String[] splitWords = fileContent.split("\\W"); // W是非单词字符,或者我忘了

StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
    int idx = fileContent.indexOf(word, stringBuilder.length());
    String delim = fileContent.substring(stringBuilder.length(), idx);
    stringBuilder.append(delim);
    
    StringBuilder output = new StringBuilder(word).reverse();
    stringBuilder.append(output);
}
// 是否有尾部分隔符?
if (fileContent.length() != stringBuilder.length()) {
    // 添加剩余部分
    stringBuilder.append(fileContent.substring(stringBuilder.length()));
}
return stringBuilder.toString();
英文:

Your code works with two changes:

  1. Replace the pattern
  2. Test for trailing delimiter

String fileContent = "Joe'); MAKE TEST random;--";
String[] splitWords = fileContent.split("\W"); // W is non word character or
I forgot

StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
    int idx = fileContent.indexOf(word, stringBuilder.length());
    String delim = fileContent.substring(stringBuilder.length(), idx);
    stringBuilder.append(delim);
    
    StringBuilder output = new StringBuilder(word).reverse();
    stringBuilder.append(output);
}
// did we have trailing delimiter ?
if(fileContent.length()!=stringBuilder.length())
{ //append remaining
    stringBuilder.append(fileContent.substring(stringBuilder.length()));
}
return stringBuilder.toString();

huangapple
  • 本文由 发表于 2020年4月9日 04:49:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61109782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定