如何用Java中的特殊字符替换替换元音? [英] How to replace replace vowels with a special character in Java?

查看:133
本文介绍了如何用Java中的特殊字符替换替换元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class ReplaceVowels {

    public static void main(String args[]) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the String:");
        String str = bf.readLine();

        char[] c = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {

            if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o'
                    || c[i] == 'u') {

                System.out.println(str.replace(c[i], '?'));

            }

        }

    }
}

为什么 str.replace 方法不起作用?我该怎么做才能使它工作?

why does the str.replace method not work? What should I do to make it work?

推荐答案

在你的代码中,你要创建一个新的字符数组,这是与字符串的长度相同,但是你没有用任何值初始化数组。

In your code, you're creating a new array of characters, which is the same length as your string, but you're not initialising the array with any values.

相反,试试:

char[] c = str.toCharArray();

然而,这不是你做的事情的最佳方式。您不需要字符数组或if语句来替换字符串中的字符:

However, this isn't the best way of doing what you're trying to do. You don't need a character array or an if statement to replace characters in a string:

String str = bf.readLine();
str.replace( 'a', '?' );
str.replace( 'e', '?' );
str.replace( 'i', '?' );
str.replace( 'o', '?' );
str.replace( 'u', '?' );
System.out.println( str );

替换函数将替换任何(和它找到的所有字符,如果字符串中不存在该字符,它将不执行任何操作。

The replace function will replace any (and all) characters it finds, or it will do nothing if that character doesn't exist in the string.

您可能还想查看使用正则表达式(正如edwga的回答中所指出的那样),这样你就可以将这5个函数调用缩短成一个:

You might also want to look into using regular expressions (as pointed out in edwga's answer), so that you can shorten those 5 function calls into one:

str.replaceAll( "[aeiou]", "?" );

这篇关于如何用Java中的特殊字符替换替换元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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