Java program to expand a String if range is given?



To expand a String if range is given, the Java code is as follows −

Example

 Live Demo

public class Demo {    public static void expand_range(String word) {       StringBuilder my_sb = new StringBuilder();       String[] str_arr = word.split(", ");       for (int i = 0; i < str_arr.length; i++){          String[] split_str = str_arr[i].split("-");          if (split_str.length == 2){             int low = Integer.parseInt(split_str[0]);             int high = Integer.parseInt(split_str[split_str.length - 1]);             while (low <= high){                my_sb.append(low + " ");                low++;             }          } else {             my_sb.append(str_arr[i] + " ");          }       }       System.out.println(my_sb.toString());    }    public static void main(String args[]){       String my_str = "1-4, 56-57, 99-101, 0-1";       System.out.println("The expanded range of given numbers is ");       expand_range(my_str);    } }

Output

The expanded range of given numbers is 1 2 3 4 56 57 99 100 101 0 1

A class named Demo contains a function named ‘expand_range’, that splits the string basedon commas, and iterates through the string and splits the numbers and increments 1 every time. This is displayed on the console. In the main function, the string is defined, and the function is called by passing this function as a parameter. Relevant message is displayed on the console.

Updated on: 2020-07-08T11:53:10+05:30

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements