java - Reverse a String without affecting special characters -
why throwing error? 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 @ java.lang.string.charat(string.java:658) @ arraygs.raws.rawsc(raws.java:22) @ arraygs.raws.main(raws.java:30)
the problematic part 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 length of ori
. reason if-condition in 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 position i
in temp
(as part of second loop) may result in java.lang.stringindexoutofboundsexception
.
Comments
Post a Comment