在不影响特殊字符的情况下反转字符串

时间:2017-08-20 13:47:43

标签: java string reverse

为什么会抛出错误?任何帮助将不胜感激

public class RAWS 
{
public String rawsc(String ori)
{
    String temp="";
    for(int i=0;i<ori.length();i++)
    {
        char c=ori.charAt(i);
        if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
            temp=c+temp;
    }
    for(int i=0;i<ori.length();i++)
    {
        char c=ori.charAt(i);
        if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
            ori.replace(c, temp.charAt(i));
    }
    for(int i=0;i<ori.length();i++)
    {
        System.out.println(ori.charAt(i));
    }
    return(ori);
}
public static void main(String[] args) 
{
    String str="a,b$c";
    RAWS ob=new RAWS();
    String new1=ob.rawsc(str);
    for(int i=0;i<new1.length();i++)
    {
        System.out.print(new1.charAt(i)+" ");
    }
}
}

编辑:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 
at java.lang.String.charAt(String.java:658) 
at arraygs.RAWS.rawsc(RAWS.java:22) 
at arraygs.RAWS.main(RAWS.java:30)

12 个答案:

答案 0 :(得分:1)

有问题的部分是

中的电话temp.charAt(i)
for(int i=0;i<ori.length();i++){
    char c=ori.charAt(i);
    if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
        ori.replace(c, temp.charAt(i));
}

字符串temp的长度可能不是ori。原因是第一个循环中的if条件

for(int i=0;i<ori.length();i++) {
    char c=ori.charAt(i);
    if(((c>=65)&&(c<=90))||((c>=97)&&(c<122)))
        temp=c+temp;
}

因此,访问i中的位置temp(作为第二个循环的一部分)可能会产生java.lang.StringIndexOutOfBoundsException

答案 1 :(得分:1)

public class Solution {  
public static void main(String[] args) {  
 System.out.println(reverseString("a,b$c"));  
}  
/**  
* Reverse string with maintaining special character in place  
*  
* Algorithm:  
* 1. create temporary array  
* 2. copy all character from original array excluding special character  
* 3. reverse the temporary array  
* 4. start copying temporary array into original if element is an alphabetic character  
* @param input  
* @return  
*/ 
public static String reverseString(String input) {  
 char[] inputArr = input.toCharArray();  
 char[] tempArr = new char[input.length()];  
 int i=0;  
 int j=0;  
 for (char ch:inputArr){  
   if(Character.isAlphabetic(ch)){  
     tempArr[i] = ch;  
     i++;  
   }  
 }  
 i--;  
 while(j<i){  
   char temp = tempArr[i];  
   tempArr[i]= tempArr[j];  
   tempArr[j]=temp;  
   j++;  
   i--;  
 }  
 for(i=0,j=0;i<input.length();i++){  
   if(Character.isAlphabetic(inputArr[i])){  
     inputArr[i]= tempArr[j++];  
   }  
 }  
 return new String(inputArr);  
}  
}  

答案 2 :(得分:0)

公共类Ex {

public static void main(String[] args) {
String ss= "Hello@@#+dnksjaf#+43@##@";
char[] c=new char[ss.length()];
String spclCharLessString="";
String spclCharLessStringrev="";

for(int i=0;i<ss.length();i++) {
    if(((ss.charAt(i)>='A'&&ss.charAt(i)<='Z')|(ss.charAt(i)>='a'&&ss.charAt(i)<='z')|(ss.charAt(i)>='0'&&ss.charAt(i)<='9'))) {
        spclCharLessString+=ss.charAt(i);
    }
    c[i]=ss.charAt(i);
}
for(int i=spclCharLessString.length()-1;i>=0;i--) {
    spclCharLessStringrev+=spclCharLessString.charAt(i);
}
int spclCharSpace=0;
for(int i=0;i<ss.length();i++) {
    if(((ss.charAt(i)>='A'&&ss.charAt(i)<='Z')|(ss.charAt(i)>='a'&&ss.charAt(i)<='z')|(ss.charAt(i)>='0'&&ss.charAt(i)<='9'))) {
        c[i]=spclCharLessStringrev.charAt(i-spclCharSpace);
    }else {
        spclCharSpace++;
    }

}
System.out.println(spclCharLessStringrev);
for(char c1:c) {
    System.out.print(c1);
}


}

}

答案 3 :(得分:0)

使用正则表达式似乎是个好主意。这是我的JavaScript解决方案。

var reverseOnlyLetters = function(S) {
let arr = S.split('')
let regex = /^[a-zA-Z]{1}$/
let i=0,j=arr.length-1;
while(i<j){
   if(regex.test(arr[i]) && regex.test(arr[j])){
       let temp = arr[i]
       arr[i]=arr[j]
       arr[j]=temp
       i++;j--
   }else{
       if(!regex.test(arr[i])) i++
       if(!regex.test(arr[j])) j--
   } 
}
return arr.join('')

};

答案 4 :(得分:0)

公共类PracticeJava {

T

}

答案 5 :(得分:0)

str=input("enter any string")
l=[]
s=""
list=list(str)
for i in str:
    k=ord(i)
    if((k>=48 and k<=57) or (k>=65 and k<=90) or(k>=97 and k<=122)):
        l.append(i)
l.reverse()
print(s.join(l))

sreevidhya bontha

答案 6 :(得分:0)

  public static void main(String[] args) {
        String str = "fed@cb%a!";
        char arr[] = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < 48 || (str.charAt(i) > 57 && str.charAt(i) < 65) || (str.charAt(i) > 90 && str.charAt(i) < 97) || str.charAt(i) > 122)
                arr[i] = str.charAt(i);
            else
                arr[i] = '0';
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            stack.push(str.charAt(i));
        }
        int i=0;
        while(!stack.isEmpty()){
            char pop = stack.pop();
            if (!(pop < 48 || (pop > 57 && pop < 65) || (pop > 90 && pop < 97) || pop > 122)){
                arr[i] = pop;
                ++i;
            }
            if(arr[i]!='0'){
                ++i;
            }
        }
        for ( i = 0; i < str.length(); i++) {
            System.out.print(arr[i]);
        }
    }
Time complexity: O(n)

答案 7 :(得分:0)

public static void main(String[] args) {
        String a = "ab$cd";
        char[] b = a.toCharArray();
        int c = b.length;
        for (int i = 0; i < c / 2; i++) {
            if (Character.isAlphabetic(b[i]) || Character.isDigit(b[i])) {
                char temp = b[i];
                b[i] = b[c - i - 1];
                b[c - i - 1] = temp;
            }
        }
    System.out.println(String.valueOf(b));
}

答案 8 :(得分:0)

公共类MuthuTest { 静态地图列表= new HashMap();

/*
 * public static int fact(int n) { if(n>1) return n*fact(n-1); else return 1; }
 */
@SuppressWarnings("deprecation")
public static void main(String[] args) {
    String j = "muthu is a good boy.";
    int v = 0;
    String[] s = j.split(" ");
    for (int h = 0; h < s.length; h++) {
        String y;
        y = s[h].replaceAll("[A-Za-z0-9]", "");

        list.put(h, y);

    }

    // MuthuTest.li(s);
    for (int u = s.length - 1; u >= 0; u--) {
        if (u == 0) {

            s[u] = s[u].replaceAll("[^A-Za-z0-9]", "");
            System.out.print(s[u] + list.get(v));

        } else {
            s[u] = s[u].replaceAll("[^A-Za-z0-9]", "");

            System.out.print(s[u] + list.get(v) + " ");
        }

        v++;
    }

}

}

答案 9 :(得分:0)

[Java]仅反转字母而不影响特殊字符的简单方法。

public class StringReverse {
    public static void main(String[] args) {
       reverseString("T@E$J#A%S");
}

//S@A$JE@T
private static void reverseString(String s){
    int len = s.length();
    char[] arr = new char[len];
    for(int i=0; i<len; i++){
        char ch = s.charAt(i);
        if(Character.isAlphabetic(ch)){
            arr[len-1-i] = ch;
        }else{
            arr[i] = ch;
        }
    }

    System.out.println(new String(arr));
}

}

答案 10 :(得分:0)

#!/usr/bin/env bash
echo "Choose from 1,2" 
read -p "Enter here : " input1
echo "Choose from a,b" 
read -p "Enter here : " input2

while true; do
case $input1+$input2 in
  1+a )
    echo "You have chosen 1 and a"
     break;;
  1+b )
    echo "You have chosen 1 and b"
    break;;
  2+a )
   echo "You have chosen 2 and a"
    break;;
  2+b )
   echo "You have chosen 2 and b"
    break;;
  *+* )
    echo "Invalid input";;
esac
done

答案 11 :(得分:0)

反转字符串而不影响任何特殊字符。请注意,它仅适用于字符串,而不适用于最终将成为字符串数组的字符串组合。

代码:

public class Info {
    
    // Input : str = "Ab,c,de!$"               o/p : ed,c,bA!$
    public static void main(String[] args) {
        String input = "Ab,c,de!$";
        char[] inputCharArray = input.toCharArray();
        reverseIgnoreSpecialCharacters(inputCharArray);
        
    }
    
    public static void reverseIgnoreSpecialCharacters(char[] charArray) {
        int j = charArray.length-1;
        int k = 0;
        for(int i = charArray.length-1; i>=0;  i--) {
            if(!(charArray[i] >= 65 && charArray[i] <=90) || !(charArray[i] >= 97 && charArray[i] <=122)) {
                charArray[j] = charArray[i];
                System.out.print(charArray[j]);
                j--;
                
            }
            else {
                charArray[k] = charArray[i];
                System.out.print(charArray[k]);
                k++;
            }       
        }   
    }
}

对于多个字符串,你可以像下面这样:

代码:

public class Info {
    
    // Input : str = "Ab,c,de!$"               o/p : ed,c,bA!$
    public static void main(String[] args) {
        String input = "Ab,c,de!$ Abhi$hek";
        String[] inputStringArray = input.split("\\ ");
        for(int i = inputStringArray.length-1; i>=0; i--) {
            char[] strArray = inputStringArray[i].toCharArray();
            reverseIgnoreSpecialCharacters(strArray);
            System.out.print(" ");
        }
        
    }
    
    public static void reverseIgnoreSpecialCharacters(char[] charArray) {
        int j = charArray.length-1;
        int k = 0;
        for(int i = charArray.length-1; i>=0;  i--) {
            if(!(charArray[i] >= 65 && charArray[i] <=90) || !(charArray[i] >= 97 && charArray[i] <=122)) {
                charArray[j] = charArray[i];
                System.out.print(charArray[j]);
                j--;
                
            }
            else {
                charArray[k] = charArray[i];
                System.out.print(charArray[k]);
                k++;
            }       
        }   
    }
}