Program opened below. You can scroll through the algorithm, Java code and output.
Program 44
Delete Repeated Characters from a Sentence
Question
Convert a sentence to uppercase and remove repeated characters, retaining the first occurrence of each character.
Algorithm
Step 1: Start the program and accept a complete sentence.
Step 2: Convert the sentence to uppercase so that letter comparisons are consistent.
Step 3: Initialise an empty string to store characters that will be retained.
Step 4: Visit each character of the original sentence from left to right.
Step 5: Store the current character in a temporary variable.
Step 6: Search the result string for the same character using an inner loop.
Step 7: If the character is already present, do not append it again.
Step 8: If the character is absent, append it to the result string.
Step 9: Continue the search and append process for all characters, including spaces and punctuation.
Step 10: This retains only the first occurrence of each character.
Step 11: Display the original sentence on a separate line.
Step 12: Display the sentence after repeated characters have been removed, then stop.
Java program
Javaimport java.util.*;
class RemoveRepeatedCharacters
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine();
String result = "";
for (int i = 0; i < s.length(); i++)
{
char ch = Character.toUpperCase(s.charAt(i));
boolean found = false;
for (int j = 0; j < result.length(); j++)
{
if (result.charAt(j) == ch)
{
found = true;
}
}
if (!found)
{
result += ch;
}
}
System.out.println("Original: " + s);
System.out.println("New sentence: " + result);
}
}Sample output
Input: COMPUTER APPLICATION
Output: Original: COMPUTER APPLICATION
New sentence: COMPUTER ALIN