First you have to put \
in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\"")
, otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10)
since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0
to k
and from k+10
to str.length()
. If you go from 0 --> k and k --> length()
you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+
since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}