首页 > Java > 正文

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

王林
发布: 2024-02-09 13:30:15
转载
1266人浏览过

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 中,而不是固定大小的数组中,因为您事先不知道将获得多少个输入。

示例代码如下所示。

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号