[英]how split a string and assign a unique 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]);
}
您可以使用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將是相同的。
嘗試
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.