I am having trouble with my code. as i run the program it displays array index out of bound exception.Please suggest what are the errors in the code.
package replacespace;
import java.util.Scanner;
public class ReplaceSpace {
/*public int calLength(char par1[]){
int count=0;
for(char c:par1){
count++;
}
return(count);
}*/
/**
*
* @param args
*/
public void replaceSpace(char str[], int length){
char[] newArray= new char[length+1];
newArray[length+1]='\0';
int position=0;
for(int i=0;i<length;i++){
if(str[i]==' '){
length=length+2;
newArray[position]='%';
newArray[position+1]='2';
newArray[position+2]='0';
position=position+3;
}
else{
newArray[position]=str[i];
position++;
}
}
String s=new String(newArray);
System.out.println(s);
}
public static void main(String[] args) {
ReplaceSpace rs= new ReplaceSpace();
String s1,sCopy;
int length;
Scanner scan= new Scanner(System.in);
System.out.println("Please enter any string");
s1=scan.nextLine();
length=s1.length();
char stringArr[]=new char[length];
stringArr =s1.toCharArray();
//length=rs.calLength(stringArr);
rs.replaceSpace(stringArr,stringArr.length);
}
}
this code is suppose to replace space in string with '%20'.