【问题标题】:how split a string and assign a unique id如何拆分字符串并分配唯一的ID
【发布时间】:2013-11-03 10:16:32
【问题描述】:

我想读取一个输入文件并将句子转换为单词,然后提供一个唯一的整数 id。

我能够将输入字符串转换为单词,但我很困惑如何为每个单词分配唯一 ID,并且需要删除重复项。 (如果输入 - 我想去康提。两个场合'to'应该得到相同的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]);
   }

【问题讨论】:

  • 旁注,如果你想打印所有元素,i&lt;st.length-1 应该是i&lt;st.length

标签: java string


【解决方案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();
        }   

    }

【讨论】:

    【解决方案2】:

    您可以为此目的使用 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 将是相同的。

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 2022-01-08
      • 2018-02-06
      • 1970-01-01
      • 2019-01-13
      • 2021-05-10
      • 2013-05-09
      相关资源
      最近更新 更多