Swarnav
Swarnav

Reputation: 3

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)

Upvotes: 0

Views: 25418

Answers (13)

Mahboob Siddiqui
Mahboob Siddiqui

Reputation: 11

Simplest Way to Do it..

    String name = "Ma@hb$oobSi#ddi$qui";
    char oldchararr[] = name.toCharArray();
    String newStr = new StringBuffer(name.replaceAll("[^A-Za-z0-9]", "")).reverse().toString();
    char newchar[] = newStr.toCharArray();
    int j = 0;
    for (int i = 0; i < oldchararr.length; i++) {
        if (Character.isAlphabetic(oldchararr[i]) || Character.isDigit(oldchararr[i])) {
            oldchararr[i] = newchar[j];
            j++;
        }
    }
    for (char c : oldchararr) {
        System.out.print(c);
    }

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

Reverse a String without affecting any special chars. Note that it is just for a String but not combination of Strings that would eventually be an array of Strings.

Code :

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

for multiple Strings, you could something like below :

Code :

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

Upvotes: 0

Suryakant Chavan
Suryakant Chavan

Reputation: 1

import java.util.HashMap;
import java.util.Map.Entry;



public class ReverseString {

    public static void main(String[] args) {
        HashMap<Character, Integer> map = new HashMap<>();
        String s = "S@3jakd*nd%4*ksdkj12";
        String str = "";
        int len = s.length();

        for (int i = len - 1; i >= 0; i--) {
            char ch = s.charAt(i);
            if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
                str = str + s.charAt(i);
            } else {

                map.put(s.charAt(i), new Integer(s.indexOf(s.charAt(i))));

            }
        }

        for (Entry<Character, Integer> entry : map.entrySet()) {

            str = str.substring(0, entry.getValue()) + entry.getKey() + str.substring(entry.getValue(), str.length());

        }
        System.out.println(str);
    }

}

Upvotes: 0

tejas madappa
tejas madappa

Reputation: 13

[Java] Simple way to reverse only alphabets without affecting special chars.

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

}

Upvotes: 0

mk7644
mk7644

Reputation: 33

public class MuthuTest { static Map list = 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++;
    }

}

}

Upvotes: 0

Shashidhar Yalagi
Shashidhar Yalagi

Reputation: 51

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

Upvotes: 0

Virendra kumar
Virendra kumar

Reputation: 1

  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)

Upvotes: 0

BONTHA SREEVIDHYA
BONTHA SREEVIDHYA

Reputation: 9

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

by sreevidhya bontha

Upvotes: 0

Gowtham Reddy
Gowtham Reddy

Reputation: 21

public class PracticeJava{

public static void main(String []args){

   String str = "\"Str!ng\"";
   System.out.println("Actual str:  "+str);
   System.out.println("Reverse str: "+reverseStrSpecial(str));

}

public static String reverseStrSpecial(String str) {
    int len = str.length();
    char[] revStrArr = new char[len];
    int j = len-1;
    for (int i=0; i <= j; ) {
        if(!Character.isAlphabetic(str.charAt(i))) {
            revStrArr[i] = str.charAt(i);
            i++;
        } else if (!Character.isAlphabetic(str.charAt(j))) {
            revStrArr[j] = str.charAt(j);
            j--;
        } else {
            revStrArr[j] = str.charAt(i);
            revStrArr[i] = str.charAt(j);
            j--;
            i++;
        }
    }

    return new String(revStrArr);
}

}

Upvotes: 2

utkarsh
utkarsh

Reputation: 1

using regex seems to be a good idea.here is my javascript solution.

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('')

};

Upvotes: 0

Sai ram
Sai ram

Reputation: 9

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


}

}

Upvotes: 0

Sriram S
Sriram S

Reputation: 543

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

Upvotes: 0

Stefan Freitag
Stefan Freitag

Reputation: 3608

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.

Upvotes: 2

Related Questions