Extract left and rightmost n characters of a string – Java


In this post, we are going to see how to extract left and rightmost ‘n’ characters from a string given by the user.  We are going to see how it’s done by a simple program in Java.


In this program, the user will be asked to enter the string, the number of leftmost characters and the number of rightmost characters he wants to extract from the given string. See the output of our program below, you will have a better idea of our program –

At first, ask the user for the string. The string length can be any number of characters.

Suppose our string is “Java is love. Java is life.”.

After getting the string count the length.

Now we have to store the characters of the string in a character array. Our char array size is the length our string.

Now we can ask the users how many characters they want to extract from the left and how many from the right.

First, ask how many characters they want to extract from the left. See the code below –

This will give the output like this –

After getting the leftmost characters, ask for the rightmost characters –

This will be the output –

Below is the complete code of our program –

Now run the program and see the output. Comment below in the comment box if you have any doubts or any suggestions or if you have a better solution of this program.

More programs on java –

Sort numbers in ascending order – Java Program

Program to count number of words in a string (multiple spaces) – Java

Program to print rectangle pattern with star and hashes – Java


You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *