繁体   English   中英

如何拆分字符串并分配唯一的ID

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM