Search code examples
javastringreverse

Reverse a String without affecting special characters


Why is it throwing an error? Any help would be appreciated

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)+" ");
    }
}
}

Editor:

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)

Solution

  • The problematic part is the call temp.charAt(i) in

    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));
    }
    

    The string temp may not have the length of ori. The reason for this is the if-condition in the first loop

    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;
    }
    

    So accessing the position i in temp (as part of the second loop) may result in the java.lang.StringIndexOutOfBoundsException.