Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove words of a string started by uppercase characters in Scala

I want to write an algorithm that removes every word started by an uppercase character in a string.

For example:

Original string: "Today is Friday the 29Th."

Desired result: "is the 29Th."

I wrote this algorithm, but it is not complete:

def removeUpperCaseChars(str: String) = {
    for (i <- 0 to str.length - 1) {
      if (str.charAt(i).isUpper) {
        var j = i
        var cont = i
        while (str.charAt(j) != " ") {
          cont += 1
        }
        val subStr = str.substring(0, i) + str.substring(cont, str.length - 1)
        println(subStr)
      }
    }
  }

It (supposedly) removes every word with uppercase characters instead of removing only the words that start with uppercase characters. And worse than that, Scala doesn't give any result.

Can anyone help me with this problem?

like image 269
undisp Avatar asked Nov 16 '25 12:11

undisp


1 Answers

With some assumptions, like words are always split with a space you can implement it like this:

scala> "Today is Friday the 29Th.".split("\\s+").filterNot(_.head.isUpper).mkString(" ")
res2: String = is the 29Th.

We don't really want to write algorithms in the way you did in scala. This is reather a way you would do this in C.

like image 83
Łukasz Avatar answered Nov 19 '25 06:11

Łukasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!