madagascar madagascar - 1 year ago 177
Scala Question

Exception Index Out Of Bounds when using deleteCharAt with StringBuilder

I want to delete duplicate char in my string with using deleteCharAt method but it's giving me an exception

def removeDuplicate(str: String): String={
var sb = new StringBuilder(str);
for(i <-0 until str.length ){
for(z <- i+1 until str.length ){
return sb.toString;}

Answer Source

As the error suggested, when i = str.length - 1, z = str.length which is out of index. And there is another problem with your code, which is you are removing character from a string while looping through it. It is usually not a good practice to do so since the string length changes every time you delete a character, and you need to keep track of that. An alternative and more intuitive way is to build a new string and add only characters that have not appeared in the new string:

def removeDuplicate(str: String):String = {
  var sb = ""
  for(i <- 0 until str.length) {
    if(! (sb contains str(i))) {
      sb += str(i)

scala> removeDuplicate("abbccssds")
res13: String = abcsd

scala> removeDuplicate("abbeedsff")
res14: String = abedsf

scala> removeDuplicate("abbeedsffgg")
res15: String = abedsfg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download