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());
}我建议您分两步解决您的问题。
首先,摄取部分:您需要接受用户输入的单词,并将每个单词存储在 arraylist<string> 中,而不是固定大小的数组中,因为您事先不知道将获得多少个输入。
示例代码如下所示。
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号