Java Program to Move All Uppercase Characters to the End
Last Updated :
31 Mar, 2023
Given a string that contains uppercase letters as well as lower case letters. The task is to move all uppercase characters at the end of the String. The uppercase characters must be in the same order as in the original string.
Input : "heLLGFg"
Output : "hegLLGF"
Input : "Hello"
Output : "elloH"
Here we are having two different approaches to get to the problem namely as follows:
- Using ASCII values of the characters.
- Using queue data structures
Approach 1: Using ASCII values of the characters.
- Iterate the character of the string one by one and checks the ASCII values of the respective character of the string.
- For all uppercase letters, ASCII values lie under [65-90] char values. Store the characters of these ASCII values in the String variable and print the string at the end of the Iteration.
Example:
Java
import java.io.*;
class GFG {
static void shiftuppercase(String m, int length)
{
String temp = "" ;
for ( int i = 0 ; i < length; ++i) {
if (m.charAt(i) >= 65 && m.charAt(i) <= 90 ) {
temp += m.charAt(i);
}
else
System.out.print(m.charAt(i));
}
System.out.print(temp);
}
public static void main(String[] args)
{
String m = "heLLGFg" ;
int length = m.length();
shiftuppercase(m, length);
}
}
|
Output:
Time Complexity: O(n) //n is the length of the string.
Space Complexity: O(1)
Approach 2: Using queue data structures
- Queue Data structure implements the First in First out concept, We use this concept and store the uppercase characters in the queue.
- Print all the characters except the uppercase characters.
- After the iteration removes all the elements from the queue.
Example:
Java
import java.io.*;
import java.util.*;
class GFG {
static void shiftuppercase(String m, int length)
{
Queue<Character> Q = new LinkedList<Character>();
String temp = "" ;
for ( int i = 0 ; i < length; ++i) {
if (m.charAt(i) >= 65 && m.charAt(i) <= 90 ) {
Q.add(m.charAt(i));
}
else
System.out.print(m.charAt(i));
}
while (Q.size() != 0 ) {
System.out.print(Q.peek());
Q.remove();
}
}
public static void main(String[] args)
{
String m = "heLLGFg" ;
int length = m.length();
shiftuppercase(m, length);
}
}
|
Output:
Time Complexity: O(N) // where N is the length of the given string.
Auxiliary Space: O(n)
Approach 3 : Using isUpperCase() method
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String m = "heLLGFg" ;
String newstr = "" ;
String upper = "" ;
for ( int i = 0 ; i < m.length(); i++) {
if (Character.isUpperCase(m.charAt(i))) {
upper += m.substring(i, i + 1 );
}
else {
newstr += m.substring(i, i + 1 );
}
}
System.out.println(newstr + upper);
}
}
|
Share your thoughts in the comments
Please Login to comment...