WAP to Split a String on Uppercase Characters

Split a String on Uppercase Characters: The given Java program takes an input string abCdefGHijkl and splits it into substrings based on the occurrence of uppercase letters. The resulting output separates the substrings wherever an uppercase letter is found, adding spaces between them. The output for the given input is ab Cdef G Hijkl.

Split a String on Uppercase Characters

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
public class InterviewPrograms42 
	 * Input =“abCdefGHijkl”; 
	 * Output: “ab Cdef G Hijkl”
	public static void main(String[] args) 
		String st = "abCdefGHijkl";
		String[] r = st.split("(?=\\p{Upper})");



Here’s a step-by-step explanation of the program:

  1. Define the main method:
    • The program starts executing from the main method.
  2. Initialize the input string:
    • The input string st is initialized with the value “abCdefGHijkl”.
  3. Split the string based on uppercase letters:
    • The split method is used on the input string st, with the regex pattern “(?=\\p{Upper})”.
    • The regex pattern “(?=\\p{Upper})” is a positive lookahead, which matches an empty string that is followed by an uppercase letter. This effectively splits the string at the positions before each uppercase letter.
    • The result of the split method is an array of substrings, which are stored in the variable r.
  4. Print the output:
    • The program uses the Arrays.stream() method to convert the array r into a stream of substrings.
    • The forEach method is used to iterate through each substring in the stream and print it using System.out::println.

For the given input “abCdefGHijkl”, the program splits the string at the positions before uppercase letters ‘C’, ‘G’, and ‘H’, resulting in substrings “ab “, “Cdef “, “G”, “Hijkl”. The program then prints each substring on a new line, with spaces separating the substrings wherever an uppercase letter was found.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment