// SplittingAtoms.kt Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2023-04-29 File created. // This program demonstrates, how a sting can be split to // substrings according to a regular expression. fun main() { var atomic_text = "\n Atoms consist of protons, neutrons, and electrons." print( atomic_text + "\n" ) var substrings_from_text = atomic_text.split( Regex( "[\n,]" ) ) for ( substring_index in 0 .. substrings_from_text.size - 1 ) { print( "\n" + substring_index + ":" + substrings_from_text[ substring_index ] ) } /* atomic_text = "" for ( substring_index in 0 .. substrings_from_text.size - 1 ) { atomic_text = atomic_text + substrings_from_text[ substring_index ] } */ // The original string is recomposed so that an empty string // is put between the substrings. atomic_text = substrings_from_text.joinToString( "" ) print( "\n\n" + atomic_text + "\n" ) substrings_from_text = atomic_text.split( Regex( "[ ]" ) ) for ( substring_index in 0 .. substrings_from_text.size - 1 ) { print( "\n" + substring_index + ":" + substrings_from_text[ substring_index ] ) } print( "\n\n" ) }