fun nonSpaceString(s: String): String {
var result = " "
for (index in 0..s.length-1) {
if (s[index] != ' ') {
result = s[index]
}
}
return result
}
fun main(){
nonSpaceString("abc d e")
}
I tried to eleminate spaces in string.
but result is holding "a" and then holding "ab" but at the end result holds nothing
CodePudding user response:
Your code runs fine, it returns abcde
.
If your aim is just to remove all spaces, it does not have to be this complicated.
"abc d e".filter { !it.isWhitespace() }
will do.
CodePudding user response:
You have initialized the result with a space character. So the result starts with a space that may confuse you. Apart from that, your function is working fine. Additionally, you can use the replace function to remove all spaces from a string
"abc d e".replace("\\s ".toRegex(), "")