首页  >  文章  >  如何将字符串标记存储到数组中

如何将字符串标记存储到数组中

王林
王林转载
2024-02-09 13:30:151238浏览

php小编草莓将为大家介绍如何将字符串标记存储到数组中。在编程过程中,我们经常需要处理字符串并将其拆分成多个标记。将这些标记存储到数组中可以方便我们对其进行处理和操作。本文将详细讲解如何使用php中的函数和方法来实现这一功能,帮助读者更好地理解和运用。无论您是初学者还是有一定经验的开发者,都可以从本文中获得有益的知识和实用的技巧。让我们一起开始吧!

问题内容

我参考了一些示例来成功提取用户输入的每个部分。但只能提取1次。应该有 2 个循环用于提取多个输入并将标记保存在数组中。我被困在阵列上,我该怎么办?

question:
write a program that accepts string tokens in the format of token1:token2:token3:token4 , where : is used as delimiter to separate tokens. there should be two functions, ingest and appearance.

ingest takes a string, and stores it in the collection.

appearance takes a string as input . it returns a normalized value
between 0 to 1,  where the value represents the percentage of
appearances of stored tokens which have input as the prefix.

state the space and time complexity of your solution.


预期结果:

ingest('mcdonal:uk:employeea')
ingest('mcdonal:hk:employeea')
ingest('mcdonal:hk:employeeb')
ingest('mcdonal:hk:employeec')
ingest('fastfood')

appearance('mcdonal')
# > 0.8
appearance('mcdonal:hk')
# > 0.6

我的代码:

String input;
   
        
 // For user input
 Scanner sentense = new Scanner(System.in);
 input = sentense.nextLine();   
 String[] ingestWords = {};
       
             
 // Use ':' to seperate input
 StringTokenizer st = new StringTokenizer(input, ":");
 while(st.hasMoreTokens()) { 
   System.out.println(st.nextToken());
 }

解决方法

我建议您分两步解决您的问题。

首先,摄取部分:您需要接受用户输入的单词,并将每个单词存储在 arraylist98c455a79ddfebb79781bff588e7b37e 中,而不是固定大小的数组中,因为您事先不知道将获得多少个输入。

示例代码如下所示。

public static void main(string[] args) {
    string input;
    list<string> ingestwords = new arraylist<>();

    scanner sentence = new scanner(system.in);
        
    while (sentence.hasnext()) {
        input = sentence.next();
            
        if (input.equals("exit")) { // to stop receiving input
            break;
        }
            
        ingestwords.add(input);         
    }
    sentence.close();
}

第二,外观部分:给定一个字符串,您需要从摄取部分迭代单词列表,并检查哪些单词以给定字符串开头。

例如,您可以创建一个像这样的辅助函数。

void hasPrefix(String word, String str) {
    return word.startsWith(str);
}

将此函数应用于 ingestwords 中的每个单词,将为您提供以 str 作为前缀的单词数。并且你可以从中算出出现的百分比。

以上是如何将字符串标记存储到数组中的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除