Find the first repeated word in a string | Java program for finding first repeated word in a string ; returns first repeated word ; break string into tokens ; hashset for storing words ; store the words of string in hashset ; if word exists return ; insert new word to set ; driver program
import java . util . * ; public class GFG { static String findFirstRepeated ( String s ) { String token [ ] = s . split ( " ▁ " ) ; HashSet < String > set = new HashSet < String > ( ) ; for ( int i = 0 ; i < token . length ; i ++ ) { if ( set . contains ( token [ i ] ) ) { return token [ i ] ; } set . add ( token [ i ] ) ; } return " NoRepetition " ; } public static void main ( String args [ ] ) { String s = " Ravi ▁ had ▁ been ▁ saying ▁ that ▁ he ▁ had ▁ been ▁ there " ; String firstWord = findFirstRepeated ( s ) ; if ( ! firstWord . equals ( " NoRepetition " ) ) System . out . println ( " First ▁ repeated ▁ word ▁ : : ▁ " + firstWord ) ; else System . out . println ( " No ▁ Repetitionn " ) ; } }