【问题标题】:Replacing the consonants in a string替换字符串中的辅音
【发布时间】:2023-03-27 17:00:01
【问题描述】:

我在写下这个函数的代码时遇到了麻烦。

替换辅音

/** Return a string that is s but with all lowercase consonants (letters of
 * the English alphabet other than the vowels a, e, i, o, u) replaced with
 * _, and all uppercase consonants replaced with ^.
 *
 * Examples: For s = "Minecraft" return "^i_e__a__".
 *           For s = "Alan Turing" return "A_a_ ^u_i__".

这是我到目前为止所做的:

String consonants = "bcdfghjklmnpqrstvwxyz";
for(int j = 0; j < consonants.length(); j++ ){
    int start = 0;
    if s.charAt(start) == consonants( I am unsure to tell it to look through the string I made)
        s.charAt(start).replace(s.substring(start,1), ("_"));
        if s.charAt(start) == s.substring(start,start+1).ToUpperCase(){
            s.charAt(start) = "'";
        }
    }
}

【问题讨论】:

标签: java string replace


【解决方案1】:

您可以使用基于负前瞻的正则表达式,或者您需要手动编写所有辅音。

String s = "Minecraft";
String m = s.replaceAll("(?![aeiouAEIOU])[a-z]", "_").replaceAll("(?![aeiouAEIOU])[A-Z]", "^");
System.out.println(m);

输出:

^i_e__a__

【讨论】:

  • 你会从“Braaaains”中得到什么?
  • 这行得通,我还想知道如何使用 for 循环使其工作。如果 s 字符串是大写字母,是否必须有 if 语句?还是我会使用内置函数替换?
【解决方案2】:
String myName = "domanokz";
myName.charAt(4) = 'x';

如果这不是您想要的:

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

或者您可以使用 StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

【讨论】:

  • 您尝试过其他解决方案吗?
  • OP 要求将字符转换为 _ 或 ^。你的例子都没有这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 2017-10-21
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2020-05-16
相关资源
最近更新 更多