Program opened below. You can scroll through the algorithm, Java code and output.
Program 72
Decode ASCII Values from a Continuous String
Question
Accept a string containing consecutive decimal ASCII values without spaces. Decode valid ASCII codes for A–Z, a–z and space (32); ignore other values.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input the encoded digit string.
Step 4: Set position=0 and output empty.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: At each position, try a three-digit value first, then a two-digit value.
Step 7: Accept a value only if it is 32, 65..90 or 97..122.
Step 8: Append the corresponding character and advance by the number of consumed digits.
Step 9: If no valid code starts at the current position, advance one digit and ignore it.
Step 10: Display the decoded text and stop.
Step 11: Stop.
Java program
Javaimport java.util.*;
class DecodeAscii {
static boolean valid(int n) {
return n == 32 || (n >= 65 && n <= 90) || (n >= 97 && n <= 122);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
if (!s.matches("[0-9]+")) {
System.out.println("INVALID INPUT");
return;
}
StringBuilder out = new StringBuilder();
int i = 0;
while (i < s.length()) {
int code = -1, len = 0;
for (int size = 3; size >= 2; size--) {
if (i + size <= s.length()) {
int value = Integer.parseInt(s.substring(i, i + size));
if (valid(value)) {
code = value;
len = size;
break;
}
}
}
if (code >= 0) {
out.append((char) code);
i += len;
}
else {
i++;
}
}
System.out.println(out);
}
}Sample output
Input: 726572
Output:
re