如何重新制作程序,以便在KOTLIN编程语言的函数参数中传递单词? [英] How to remake the program so that words are passed in function arguments in the KOTLIN programming language?

查看:51
本文介绍了如何重新制作程序,以便在KOTLIN编程语言的函数参数中传递单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要创建一个实现附加算法的函数,函数参数中的所有单词都将传递给该算法.

Need to create a function that implements the attached algorithm, to which all words are passed in the function arguments.

例如: f("dfd" dd"ddd");

我的代码:

    fun main() {
    var s = readLine();
    var w = Array(128){0} //To mark characters from a word 1
    var g = Array(128){0}//When we encounter a space, we add units from the first array to the corresponding elements of the second, zeroing them in the first.
    if(s!=null)
    {
        for(c in s)
        {
            if(c.toInt() > 127 || c.toInt()<0) {
                println("Input error, try again");
                return;
            }
            //Checking for space.
            if(c.toInt() != 32) w[c.toInt()] = 1;
            else
                for(k in 0..127)
                {
                    if(w[k] == 1)
                    {
                        g[k] += 1;
                        w[k]  = 0;
                    }
                }
        }
        //For the last word, if there was no space after it.
        for(k in 0..127)
        {
            if(w[k] == 1)
            {
                g[k] += 1;
                w[k]  = 0;
            }
        }
    }
    //Displaying matched characters to the screen
    for(k in 0..127)
    {
        if(g[k]>1)
        {
            println(k.toChar());
        }
    }
}

该程序搜索与字符串中至少两个单词匹配的字符

This program searches for characters that match at least two words in a string

示例

  • 输入:世界您好
  • 输出:lo
  • input: hello world
  • output: lo

推荐答案

在Kotlin中已经有针对这些工具的实用程序,我强烈建议您在问这些类型的问题之前先阅读文档.

There's already utilities for these in Kotlin, I highly recommend you to read the docs before asking these type of questions.

groupingBy 应该做什么?你想要的:

The groupingBy should do what you want:

readLine()?.let { input ->
    input.groupingBy { it }.eachCount()
        .forEach { if (it.value > 1 && it.key != ' ') println(it.key) }
}

这篇关于如何重新制作程序,以便在KOTLIN编程语言的函数参数中传递单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆