简体   繁体   中英

Reverse string without changing the position of special character using regex

class der{
    public static void maxLength(String str) {
        String s = " ";
        s = str.replaceAll("[^a-z]+", " ");
        String rev = " ";
        char ch[] = s.toCharArray();
        for(int i =ch.length-1; i>=0 ; i--){
            rev = rev + ch[i];
        }
        System.out.println(rev);
    }
    public static void main(String[] args){
        String str = "a@utom!at$ion@";
        maxLength(str);
    }
}

I tried the above with regex function where i first tried to remove special character and then reverse the string. But is there any option to add special character back again to the reverse strings? My o/p for the current code is this noi ta motu a so in blank space i want to put the special character again.

You may use this Java code:

String str = "a@utom!at$ion@";
// \W+ matches 1+ of any non-word characters
Matcher m = Pattern.compile("\\W+").matcher(str);
StringBuilder sb = new StringBuilder();
int start=0;
// loop through the matches of \W+
while (m.find()) {
   // append reverse of substring before current match
   // and then the match itself is appended in buffer
   sb
   .append(new StringBuilder(str.substring(start, m.start())).reverse())
   .append(m.group());
   start = m.end();
}
// append remaining part after last match in buffer
sb.append(new StringBuilder(str.substring(start)).reverse());
// print the results
System.out.println(sb);

Output:

a@motu!ta$noi@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM