Program opened below. You can scroll through the algorithm, Java code and output.

Delete Repeated Characters from a Sentence

Download .java

Question

Convert a sentence to uppercase and remove repeated characters, retaining the first occurrence of each character.

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
import 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);
    }
}
Input: COMPUTER APPLICATION Output: Original: COMPUTER APPLICATION New sentence: COMPUTER ALIN
← Previous Program 44 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.