Java: Rearrange the alphabets in the order followed by the sum of digits
Java Basic: Exercise-192 with Solution
Rearrange Letters and Sum Digits
Write a Java program to rearrange the alphabets in the order followed by the sum of digits in a given string containing uppercase alphabets and integer digits (from 0 to 9).
Visual Presentation:
Sample Solution:
Java Code:
// Import necessary Java utility and language packages
import java.util.*;
import java.lang.*;
// Main class for the solution
public class Solution {
// Constant representing the maximum number of characters
static final int MAX_CHAR = 20;
// Main method to execute the solution
public static void main(String args[]) {
// Input string with alphanumeric characters
String str1 = "AND456HSE8";
// Print the result of the arrange_String_nums function
System.out.println(arrange_String_nums(str1));
}
// Function to arrange uppercase characters and sum of numbers in the given string
static String arrange_String_nums(String str1) {
// Array to count the occurrences of each uppercase character
int char_count[] = new int[MAX_CHAR];
// Variable to store the sum of numeric characters
int sum_num = 0;
// Iterate through the characters in the input string
for (int i = 0; i < str1.length(); i++) {
// Check if the character is uppercase and update the char_count array
if (Character.isUpperCase(str1.charAt(i)))
char_count[str1.charAt(i) - 'A']++;
else
// Accumulate the numeric characters for sum
sum_num = sum_num + (str1.charAt(i) - '0');
}
// Initialize a string to store the rearranged characters
String rarr_part = "";
// Iterate through the characters using their ASCII values
for (int i = 0; i < MAX_CHAR; i++) {
// Convert ASCII value to corresponding character
char ch = (char)('A' + i);
// Append the characters to the result string based on their occurrences
while (char_count[i]-- != 0)
rarr_part = rarr_part + ch;
}
// If the sum of numeric characters is greater than 0, append it to the result string
if (sum_num > 0)
rarr_part = rarr_part + sum_num;
// Return the rearranged string
return rarr_part;
}
}
Sample Output:
ADEHNS23
Flowchart:
Java Code Editor:
Company: Facebook
Contribute your code and comments through Disqus.
Previous: Write a Java program to test whether there are two integers x and y such that x^2 + y^2 is equal to a given positive number.
Next: Write a Java program that accept an integer and find the sum of all the elements from all possible subsets of a set formed by first n natural numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-192.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics