Java program to expand a String if range is given?
Last Updated :
29 Jul, 2022
Suppose we have given a string in which some ranges as specified and we have to place the numbers which is between the given range in the specified place as provided and depicted in the illustration below as follows for a better understanding.
Illustration:
Input : string x = "1-5, 8, 11-14, 18, 20, 26-29"
Output : string y = "1, 2, 3, 4, 5, 8, 11, 12,
13, 14, 18, 20, 26, 27, 28, 29"
Approach:
In order to solve the above problem, we can follow the below approach:
- First, we have to split the String into String[] array. We have to split the String where we found - symbol.
- Now we have a String[] array with the elements. Now we just go to the first index last element i.e. 1 and the preceding index first element of the String[] array say it be 5.
- After that with the help of for loop, we can add the numbers which are between 1 and 5 and store them in the String variable.
- The above process continues till the length of the string array.
Note:
With the help of Collections and various utility methods we can solve the problem easily but the Collections concept is not a good option performance-wise. If we go through Collections, performance is reduced and time complexity is also increased. There in the below program we explicitly define our own split method and logic.
Implementation: Here we will now be proposing and discussing all three scenarios with help of a clean java program as follows:
Example 1:
Java
// Java program to Expand a String if Range is Given
// Main class
public class Solution {
// Main driver method
public static void expand(String word)
{
// Creating an object of StringBuffer class to
// make a modifiable string object
StringBuilder sb = new StringBuilder();
// Get all intervals
String[] strArr = word.split(", ");
// Traverse through every interval
for (int i = 0; i < strArr.length; i++) {
// Get lower and upper
String[] a = strArr[i].split("-");
// Setting high and low counters
if (a.length == 2) {
int low = Integer.parseInt(a[0]);
int high
= Integer.parseInt(a[a.length - 1]);
// Condition check holds true
// Till low counter is lesser or equal to
// high counter
while (low <= high) {
// Append all numbers
sb.append(low + " ");
low++;
}
}
// If we reaches here then
// High counter exceeds lower counter
else {
sb.append(strArr[i] + " ");
}
}
// Print the modifiable string
System.out.println(sb.toString());
}
// Method 2
// Main driver method
public static void main(String args[])
{
// Custom input string as input
String s = "1-5, 8, 11-14, 18, 20, 26-29";
expand(s);
}
}
Output: 1 2 3 4 5 8 11 12 13 14 18 20 26 27 28 29
Example 2:
Java
// Java Program to Illustrate Expansion of String
// Main class
public class StringExpand {
// Method 1
// To split the string
static String[] split(String st)
{
// Count how many words in our string
// Irrespective of spaces
int wc = countWords(st);
String w[] = new String[wc];
char[] c = st.toCharArray();
int k = 0;
for (int i = 0; i < c.length; i++) {
// Initially declaring and initializing
// string as empty
String s = "";
// Whenever we found an non-space character
while (i < c.length && c[i] != ' ') {
// Concat with the String s
// Increment the value of i
s = s + c[i];
i++;
}
// If the String is not empty
if (s.length() != 0) {
// Add the String to the String[]
// array
w[k] = s;
k++;
}
}
// Returning the string array
return w;
}
// Method 2
// To count the number of words in a string
static int countWords(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++) {
// The below condition to check
// whether the first character is
// space or not
if (i == 0 && str.charAt(i) != ' '
|| str.charAt(i) != ' '
&& str.charAt(i - 1) == ' ') {
count++;
}
}
// Returning the count
return count;
}
// Method 3
// To expand the string
public static void expand(String s)
{
String p = s;
String[] arr = p.split("\\-");
String k = "";
// Traversing over array using for loop
for (int i = 0; i < arr.length; i++) {
// Case 1
if (i != arr.length - 1) {
String[] arr1 = arr[i].split(", ");
String[] arr2 = arr[i + 1].split(", ");
int a = Integer.parseInt(
arr1[arr1.length - 1]);
int b = Integer.parseInt(arr2[0]);
for (int j = a + 1; j < b; j++) {
arr[i] = arr[i] + ", " + j;
}
}
// Case 2
if (k != "")
k = k + ", " + arr[i];
// Case 3
else
k = k + arr[i];
}
// Print the expanded string
System.out.println(k);
}
// Method 4
// Main driver method
public static void main(String[] args)
{
// Custom string input
String s = "1-5, 8, 11-14, 18, 20, 26-29";
// Calling the method 3 to
// expand the string
expand(s);
}
}
Output: 1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29
Example 3:
Java
// Java program to Expand a String if Range is Given
// Main class
// GenerateStringOnRange
class GFG {
// Method 1
// To generate string on range
public static String generateStringOn(String input)
{
String[] words = input.split(" ");
// Initially setting up range
String[] ranges = null;
int number = 0;
// Creating a StringBuffer object so that
// we can modify the string
StringBuffer buffer = new StringBuffer();
// Looking out for words by
// iterating using for each loop
for (String word : words) {
// To be replaced by
// using replace() method
word = word.replace(",", "");
// If word is containing "-" character
if (word.contains("-")) {
ranges = word.split("-");
number = Integer.parseInt(ranges[0]);
// Till number is within range
while (number
<= Integer.parseInt(ranges[1])) {
// Append , in between them
buffer.append(number + ", ");
number++;
}
}
// If we reaches here then
// word does contains "-"
else {
buffer.append(word + ", ");
}
}
// Return the StringBuffer object
return buffer.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom input string
String input = "1-5, 8, 11-14, 18, 20, 26-29";
// Calling the method 1 as created above
System.out.println(generateStringOn(input));
}
}
Output1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29,
Similar Reads
Java Program to Get a Character from a String
Given a String str, the task is to get a specific character from that String at a specific index. Examples:Input: str = "Geeks", index = 2Output: eInput: str = "GeeksForGeeks", index = 5Output: F Below are various ways to do so: Using String.charAt() method: Get the string and the indexGet the speci
5 min read
Reverse words in a given String in Java
Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in J
3 min read
Insert a String into another String in Java
Given a String, the task is to insert another string in between the given String at a particular specified index in Java. Examples: Input: originalString = "GeeksGeeks", stringToBeInserted = "For", index = 4 Output: "GeeksForGeeks" Input: originalString = "Computer Portal", stringToBeInserted = "Sci
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections.
1 min read
StringReader read(char[], int, int) method in Java with Examples
The read(char[], int, int) method of StringReader Class in Java is used to read the specified length characters into an array at a specified offset. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while r
3 min read
Java Program to Implement Suffix Array
A Suffix Array is a fundamental data structure used in string processing and computational biology. It represents an array of all suffixes of a given string, sorted lexicographically. Suffix arrays find applications in pattern matching, substring search, text compression, and bioinformatics, among o
3 min read
Searching For Characters and Substring in a String in Java
Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.Searching for a Character in a
5 min read
Java String join() with examples
The java.lang.string.join() method concatenates the given elements with the delimiter and returns the concatenated string.Note that if an element is null, then null is added.The join() method is included in java string since JDK 1.8. There are two types of join() methods in java string. :public stat
2 min read
Java.lang.String class in Java | Set 2
Java.lang.String class in Java | Set 1 In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable. Now lets discuss some of the methods provided by String class. Methods: public int codePointAt(int index) - It takes as paramet
5 min read
Java Program to Split the array and add the first part to the end
There is a given an array and split it from a specified position, and move the first part of array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] =
2 min read