java - Hashtag Uniqueness -


i trying find unique hashtags tweet user inputs. brother helping me, had leave. anyway, have code find number of times word used in input, need know number of different hashtags used. example, in input "#one #two blue red #one #green four", there 3 unique hashtags #one, #two, , #green. cannot figure out how code this.

import java.util.arraylist; import java.util.arrays; import java.util.scanner;  public class tweet {   public static void main(string[] args) { scanner hashtag = new scanner( system.in ); system.out.println( "please enter line of text" ); string userinput = hashtag.nextline();  userinput = userinput.tolowercase();  userinput = userinput.replaceall( "\\w", " " );     // strip out non words. userinput = userinput.replaceall( "  ", " " );      // strip out double spaces                                                     //   created stripping out non words                                                     //   in first place! string[] tokens = userinput.split( " " ); system.out.println( userinput );  arraylist< string > tweet = new arraylist< string >();  tweet.addall( arrays.aslist( tokens ) );  int count = 0;  for( int = 0; < tweet.size(); i++ ) {     system.out.printf( "%s: ", tweet.get( ) );     for( int j = 0; j < tweet.size(); j++ )     {         if( tweet.get( ).equals( tweet.get( j ) ) )             count++;         if( tweet.get( ).equals( tweet.get( j ) ) && count > 1 )             tweet.remove( j );                      // after having counted @ least     }                                               // one, remove duplicates list             system.out.printf( "%d\n", count );     count = 0; } 

} }

here's working code can use.

i removed string replacements because i'm not sure why you'd want remove non-word characters -- you'd removing '#' on hashtags. , multiple spaces not problem -- split() turn them harmless empty strings.

import java.util.hashset; import java.util.scanner; import java.util.set;  public class hashtags {      public static void main(string[] args) {         scanner scanner = new scanner(system.in);         system.out.println("please enter line of text");         string tweet = scanner.nextline();         set<string> hashtags = gethashtags(tweet);               system.out.println(hashtags.tostring());     }      public static set<string> gethashtags(string tweet) {         string[] words = tweet.split(" ");         set<string> hashtags = new hashset<string>();         (string word : words) {             if (word.startswith("#")) {                 hashtags.add(word);             }         }         return hashtags;     } } 

here's output sample run:

please enter line of text #one #two blue red #one #green 4     #jaja hg [#one, #two, #jaja, #green] 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -