如何将字符串标记存储到数组中
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中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章
刺客信条阴影:贝壳谜语解决方案
4 周前
By DDD
Windows 11 KB5054979中的新功能以及如何解决更新问题
3 周前
By DDD
在哪里可以找到原子中的起重机控制钥匙卡
4 周前
By DDD
<🎜>:死铁路 - 如何完成所有挑战
1 个月前
By DDD
Atomfall指南:项目位置,任务指南和技巧
1 个月前
By DDD

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

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