2013-11-03 52 views
0

我想读取输入文件并将其转换为单词,然后提供唯一的整数ID。如何拆分字符串并分配唯一的ID

我能够将输入字符串转换为单词,但我很困惑如何为每个单词指定唯一的ID并需要删除重复项。 (如果输入 - 我想去康提两个场合“到”应该得到相同的ID。)

这是我的代码:

Scanner sc = new Scanner(System.in); 

System.out.println("enter the word"); 

String s= sc.nextLine(); 
String st[] =s.split(" "); 
    for(int i=0;i<st.length-1 ;i++) 
    { 
     System.out.println(st[i]); 
    } 
+0

侧面说明,'我 Maroun

回答

1

您可以使用UUID和HashMap为了这个目的:

Map<String, String> map = new HashMap<String, String>(); // storage for all word-id pairs 

/* here insert your resulting array from scanner and split as collectionOfWords */ 
for (String yourNextWord : collectionOfWords) { 

String id = UUID.randomUUID();  // this one generates a unique string id 
map.put(yourNextWord, id); 

} 

在这个过程中,hashmap会将重复项替换为关键字,因此您将始终拥有1个且对于1个单词的许多副本具有相同项。因此,他们的ID将是相同的。

1

尝试

public class test { 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     HashMap<Integer, String> store = new HashMap<Integer,String>(); 

     System.out.println("enter the word"); 

     String s= sc.nextLine(); 
     String st[] =s.split(" "); 
     Integer uniqueId=1; 

     for(int i=0;i<st.length;i++) 
     { 
      if(!store.values().contains(st[i])){ 
       store.put(uniqueId, st[i]); 
       uniqueId = uniqueId+1; 
      }        
     } 

     for (Integer id: store.keySet()){ 
      String key =id.toString(); 
      String value = store.get(id).toString(); 
      System.out.println(key + " " + value); 

      } 
     sc.close(); 
     } 

    } 
相关问题