0

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

12
  • Off topic suggestion: System.out.println(" "+sb); could be System.out.println(sb.toString()); Commented May 7, 2014 at 7:13
  • @Totò : thanks mate but i can not use it as the output is further processed!! :) Commented May 7, 2014 at 7:17
  • Your error talks of indexOf, not setCharAt Commented May 7, 2014 at 7:17
  • 1
    @Totò ... or just System.out.println(sb) Commented May 7, 2014 at 7:17
  • If you already know the index of the character you want to replace, why not use sb.setCharAt(4, sb.charAt(0)) ? Commented May 7, 2014 at 7:19

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

@dimitrisli : is there a way around without using String wrapper?
@NoobEditor if you are just using ascii, then cast as an int should work too.
0

Try to Add null string

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.