Repeated word in a String in Java

Repeated word in a String Java
Problem Statement:
Find and display the repeated words in a string (words are separated by one or more blank spaces).
The repeated words are found using the "blank space" in the String.

Explanation:

  • After getting the string value from the user.
  • Split them using the method "split"[string.split(" ")] and add them to a string array.
  • Using two for loops(line 18 & line21) for finding the same word in the array(string splitted into the array).
  • "Cnt" is the counter value for no of times the word repeated.
  • Main Logic: In the second array, the strings of the array are compared using the iterating elements (I & j=i+1).
  • At the end of the second array, the word is printed if the cnt(count) value is greater than zero.
Code(Java):
package starkeecode;

import java.util.Scanner;

/**
 *
 * @author StarkeeCode
 */
public class StarkeeCode {

    public static void main(String[] args) {
    
        String s;
        Scanner sc = new Scanner(System.in);
        int i=0,count;
        s=sc.nextLine();
        String[] str=s.split(" ");
        for(i=0;i<str.length;i++)/*using bubble sort*/
        {
            count=0;
            for(int j=i+1;j<str.length-1;j++)
            {
                if(str[i].equals(str[j]))
                {count++;
                str[j]=String.valueOf(j);
                }
            }
                if(count>0)
                System.out.println(str[i]+ " ");
        }
}

Output:

[You can mail us your suggestions and feedback]

Post a Comment

0 Comments