 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements
 