【问题标题】:Replacing char in strings-changing elements in array替换数组中字符串更改元素中的字符
【发布时间】:2020-04-18 20:48:46
【问题描述】:

我有两个目标:

  1. 从用户输入中获取两个字符串。第一个字符串必须具有与第二个辅音相同数量的元音。
  2. 用第一个字符串中的连续辅音替换第二个字符串中的每个元音。

例子:

Input1: kajak   
Input2: kajaka
Output: kkjjkk

我已经成功实现了第一个目标。但是我对第二个目标有疑问 - 更改数组中的字母。 我认为问题在于数组部分charSecond[i] = charFirst[i],因为输入的大小不同。

编辑:我忘记在我的元音列表中添加大写字母 - 但请忽略它,我会修复它。

import java.util.Scanner;

public class Zad2 {
        public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        do {
            System.out.println("Provide two strings: ");
            String firstString = scn.next();
            String secondString = scn.next();
            char charSecond[] = secondString.toCharArray();

            String firstWithoutVowels = firstString.replaceAll("[aeiouyAEIOUY]", "");
            String secondWithoutConsonants = secondString.replaceAll("[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]", "");
            char charFirst[] = firstWithoutVowels.toCharArray();
            StringBuffer lengthOfFirst = new StringBuffer(firstWithoutVowels);
            StringBuffer lengthOfSecond = new StringBuffer(secondWithoutConsonants);
            if (lengthOfFirst.length() == lengthOfSecond.length()) {

                for (int i = 0; i < charSecond.length; i++) {
                    if (charSecond[i] == 'a' || charSecond[i] == 'e' || charSecond[i] == 'i' || charSecond[i] == 'o' || charSecond[i] == 'u' || charSecond[i] == 'y') {
                        charSecond[i] =  charFirst[i];
                    }
                }
                for (int i = 0; i < charSecond.length; i++) {
                    System.out.print(charSecond[i]);
                }
                break;
            } else {
                System.out.println("Wrong");
            }

        }
        while (true);

    }
}

【问题讨论】:

  • 您好,我刚刚编辑了帖子-现在有关于特定问题替换字母的信息在数组中。我的问题不能在 Code Review 上发布-因为它不是优化或安全问题/对工作代码的审查(我的回答是基于 Codereview 网站上的“我可以在这里问什么主题?”)我想对错误的词表示抱歉我在我的帖子中使用过,现在应该是正确的。
  • 感谢您检查 Code Review 的规则 AdamK。你是对的,这将是题外话。

标签: java string


【解决方案1】:

if (lengthOfFirst.length() == lengthOfSecond.length())条件之前初始化int c = 0

替换代码(第一个 for 循环),如下所示:

for (int i = 0; i < charSecond.length; i++) {
    if (charSecond[i] == 'a' || charSecond[i] == 'e' || charSecond[i] == 'i' || charSecond[i] == 'o' || charSecond[i] == 'u' || charSecond[i] == 'y') {
        charSecond[i] =  charFirst[c];
        c++;
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-13
    • 2017-05-14
    • 2014-05-07
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多