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></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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

Atom编辑器mac版下载
最流行的的开源编辑器

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)