Question

My requirement is pretty simple, fetch a char location and replace it with another.
Only catch is that, the char and its index comes at run time and can not be hard-coded.

Dummy code of my actual implementation :

public static void main(String args[])
{
   StringBuilder sb = new StringBuilder("just going nuts")  ;
   System.out.println(" "+sb);
   //System.out.println(sb.charAt(4)); //this works
   sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0)); //line 8 -error line
   System.out.println(" "+sb);
}

I even tried enclosing char in quotes :

sb.setCharAt(sb.indexOf(( "\""+sb.charAt(4)+"\"" )), sb.charAt(0));

but still same error

Error

line no:8: cannot find symbol
symbol : method indexOf(char)
location: class java.lang.StringBuilder
sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0));

I am not very fluent in Java but couldn't find setCharAt function examples having dynamic values like in this case!!

Was it helpful?

Solution

The error is because indexOf is expecting a String not a char so all you have to do is wrap it with String.valueOf

sb.setCharAt(sb.indexOf(String.valueOf((sb.charAt(4)))), sb.charAt(0));

outputs

 just going nuts
 justjgoing nuts

Modern IDEs should catch this compile time error while you type even offer the solution (in the case below IntelliJ):

enter image description here

OTHER TIPS

Try to Add null string

sb.setCharAt(sb.indexOf((sb.charAt(4))+""), sb.charAt(0));

As sb.indexOf() works with string not chatacters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top