- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to replace duplicate whitespaces in a String in Kotlin?
In order to remove extra whitespaces in a string, we will use the replace() function along with toRegex() function from the String class. To replace all the consecutive whitespaces with a single space " ", use the replace() function with the regular expression "\s+" which matches with one or more whitespace characters.
Example – Removing extra whitespaces in Kotlin
Take a look at the following example −
fun main(args: Array<String>) { var myString = "Removing ex tra spa ce from String" println("Input String:
" + myString) // removing duplicate whitespace println("
Extra whitespaces removed:
" + myString.replace("\s+".toRegex(), " ")) // removing all the whitespaces println("
After removing all the whitespaces:
" + myString.replace("\s+".toRegex(), "")) }
Output
It will generate the following output −
Input String: Removing ex tra spa ce from String Extra whitespaces removed: Removing ex tra spa ce from String After removing all the whitespaces: RemovingextraspacefromString
You can use the use the regular expression "\s{2,}" which matches with exactly two or more whitespace characters.
fun main(args: Array<String>) { var myString = "Use Coding Ground to Compile and Execute Kotlin Codes" println("Input String:
" + myString) // removing consecutive double whitespaces println("
After removing double whitespaces:
" + myString.replace("\s{2,}".toRegex(), " ")) }
Output
It will pick consecutive whitespaces in the given string and replace them with single whitespaces.
Input String: Use Coding Ground to Compile and Execute Kotlin Codes After removing double whitespaces: Use Coding Ground to Compile and Execute Kotlin Codes
- Related Articles
- Remove the whitespaces from a string using replace() in JavaScript?
- Python - Replace duplicate Occurrence in String
- C# Program to remove whitespaces in a string
- Shedding a string off whitespaces in JavaScript
- Delete all whitespaces from a String in Java
- How to Replace characters in a Golang string?
- How to replace line breaks in a string in C#?
- How to replace “and” in a string with “&” in R?
- How to replace substring in string in TypeScript?
- Java Program to Remove All Whitespaces from a String
- Golang program to remove all whitespaces from a string
- How to find a replace a word in a string in C#?
- How to print duplicate characters in a String using C#?
- How to search and replace texts in a string in Golang?
- How to convert String to Long in Kotlin?

Advertisements