我可以改进这个 Pig-Latin 转换器吗?

发布于 2024-09-12 20:50:27 字数 1456 浏览 9 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

漫雪独思 2024-09-19 20:50:27

我将重写 isVowel(char ch) 如下:

return "aeiou".indexOf(ch) != -1;

我将编写以下内容:

// String first = word.substring(position, word.length());
   String first = word.substring(position);

我还将重命名方法名称以遵循编码约定。

当然,对于我来说,我也会使用正则表达式而不是 substringfor 循环。

System.out.println("string".replaceAll("([^aeiou]+)(.*)", "$2$1ay"));
// ingstray

参考文献

I'd rewrite isVowel(char ch) as follows:

return "aeiou".indexOf(ch) != -1;

And I'd write the following instead:

// String first = word.substring(position, word.length());
   String first = word.substring(position);

I'd also rename method names to follow coding convention.

And of course, being me, I'd also use regex instead of substring and for loop.

System.out.println("string".replaceAll("([^aeiou]+)(.*)", "$2$1ay"));
// ingstray

References

深空失忆 2024-09-19 20:50:27

免责声明:我不懂 Java。

反向逻辑令人困惑,请这样编写您的 if 语句:

    if (IsVowel(word.charAt(0))) {
        return word + "way";
    } else {
        for (int i= 0; i < word.length(); i++) {

        // ...

        return first + second;
    }

您甚至可以删除 else

IsVowel 可能需要是私有的。它还可以使用单个 || 链或 "".indexOf (或 Java 中的任何内容)进行重写。

您的 for 逻辑可以简化为一个简短的 while

        while (position < word.length() && !IsVowel(word.charAt(position)) {
            ++position;
        }

Disclaimer: I don't know Java.

Inverted logic is confusing please write your if statement as such:

    if (IsVowel(word.charAt(0))) {
        return word + "way";
    } else {
        for (int i= 0; i < word.length(); i++) {

        // ...

        return first + second;
    }

You can even drop the else.

IsVowel may need to be private. It can also be rewritten using a single || chain, or as a "".indexOf (or whatever it is in Java).

Your for logic can be simplified int a short while:

        while (position < word.length() && !IsVowel(word.charAt(position)) {
            ++position;
        }
浊酒尽余欢 2024-09-19 20:50:27

这是一个完整的重写,如果您知道如何阅读正则表达式,则可以使代码更具可读性:

String[] words =
    "nix scram stupid beast dough happy question another if".split(" ");

for (String word : words) {
    System.out.printf("%s -> %s%n", word,
        ("w" + word).replaceAll(
            "w(qu|[^aeiou]+|(?<=(w)))([a-z]*)",
            "$3-$1$2ay"
        )
    );
}

此打印 (as see on ideone.com< /a>):

nix -> ix-nay
scram -> am-scray
stupid -> upid-stay
beast -> east-bay
dough -> ough-day
happy -> appy-hay
question -> estion-quay
another -> another-way
if -> if-way

请注意,question 变为 estion-quay,根据 维基百科文章。事实上,以上文字和翻译均摘自文章。

正则表达式的工作方式如下:

  • 首先,所有单词都以 w 为前缀,以防需要。
  • 然后,跳过 w,查找 qu< /code> 或非空辅音序列。如果两者都找不到,则实际单词以元音开头,因此使用捕获后行捕获 w
  • 然后只需重新排列组件即可获得翻译

即:

"skip" dummy w
|
w(qu|[^aeiou]+|(?<=(w)))([a-z]*)   -->  $3-$1$2ay
 \                2\_/ /\______/
  \_________1_________/    3

References

Here's a complete rewrite that makes the code more readable if you know how to read regex:

String[] words =
    "nix scram stupid beast dough happy question another if".split(" ");

for (String word : words) {
    System.out.printf("%s -> %s%n", word,
        ("w" + word).replaceAll(
            "w(qu|[^aeiou]+|(?<=(w)))([a-z]*)",
            "$3-$1$2ay"
        )
    );
}

This prints (as seen on ideone.com):

nix -> ix-nay
scram -> am-scray
stupid -> upid-stay
beast -> east-bay
dough -> ough-day
happy -> appy-hay
question -> estion-quay
another -> another-way
if -> if-way

Note that question becomes estion-quay, which is the correct translation according to Wikipedia article. In fact, the above words and translations are taken from the article.

The way the regex work is as follows:

  • First, all words are prefixed with w just in case it's needed
  • Then, skipping that w, look for either qu or a non-empty sequence of consonants. If neither can be found, then the actual word starts with a vowel, so grab the w using capturing lookbehind
  • Then just rearrange the components to get the translation

That is:

"skip" dummy w
|
w(qu|[^aeiou]+|(?<=(w)))([a-z]*)   -->  $3-$1$2ay
 \                2\_/ /\______/
  \_________1_________/    3

References

莫相离 2024-09-19 20:50:27

我知道这个问题已经存在一年多了,但我想我应该对其进行修改。这段代码有几处改进。

public String convert(String word)
{
    int position = 0;
    while(!isVowel(word.charAt(position)))
    {
        ++position;
    }
    if(position == 0)
    {
        return word + "-way";
    }
    else if(word.charAt(0) == 'q')
    {
        ++position;
    }
    return word.substring(position) + "-" + word.substring(0, position) + "ay";
}
public boolean isVowel(char character) 
{
    switch(character)
    {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            return true;
        default:
            return false;
    }
}

首先代码会找到第一个元音的位置,然后跳出循环。这比使用 for 循环遍历每个字母并使用 break 更简单;跳出循环。其次,这将匹配维基百科网站上的所有测试用例。最后,由于 char 实际上是有限范围的 int,因此可以使用 switch 语句来提高性能和可读性。

I know this question is well over a year old, but I thought I would put my modification of it. There are several improvements in this code.

public String convert(String word)
{
    int position = 0;
    while(!isVowel(word.charAt(position)))
    {
        ++position;
    }
    if(position == 0)
    {
        return word + "-way";
    }
    else if(word.charAt(0) == 'q')
    {
        ++position;
    }
    return word.substring(position) + "-" + word.substring(0, position) + "ay";
}
public boolean isVowel(char character) 
{
    switch(character)
    {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            return true;
        default:
            return false;
    }
}

First the code will find the position of the first vowel, and then jump out of the loop. This is simpler than using a for loop to iterate through each letter and using break; to jump out of the loop. Secondly, this will match all the testcases on the Wikipedia site. Lastly, since chars are actually a limited range int, a switch statement can be used to improve performance and readability.

妄断弥空 2024-09-19 20:50:27

严格来说这并不是一种改进,但 Java 约定规定方法应以小写字母开头。

Not strictly an improvement as such, but Java convention dictates that methods should start with a lowercase letter.

兮子 2024-09-19 20:50:27

我已经离开 Java 好几年了,但总的来说,你的代码看起来不错。如果您想挑剔,这里有一些评论:

  • 添加评论。它不必遵循 Javadoc 规范,但至少明确地描述接受的参数和预期的返回值,并且可能给出一些关于它如何工作的提示(根据第一个字符是否是元音而表现不同)
  • 你可能想要捕获 IndexOutOfBoundsException ,我认为如果您向其传递零长度字符串,可能会发生这种情况。
  • 方法名称应该小写。
  • IsVowel 可以重写 return c == 'a' || c == 'e' 等等。由于短路,比较次数方面的性能应该相似。

I'm years removed from Java, but overall, your code looks fine. If you wanted to be nitpicky, here are some comments:

  • Add comments. It doesn't have to follow the Javadoc specification, but at least explicitly describe the accepted argument and the expected return value and perhaps give some hint as to how it works (behaving differently depending on whether the first character is a vowel)
  • You might want to catch IndexOutOfBoundsException, which I think might happen if you pass it a zero length string.
  • Method names should be lower case.
  • IsVowel can be rewritten return c == 'a' || c == 'e' and so on. Due to short-circuiting, the performance in terms of number of comparisons should be similar.
过期情话 2024-09-19 20:50:27

这是作业吗?如果是这样,请将其标记为这样。

  • 不清楚“诚实”或“镱”的预期行为是什么。
  • 它不尊重大写字母(“Foo”应该变成“Oofay”,AEIOU 也是元音)。
  • 如果您传入空字符串,它会崩溃。

Is this homework? If so, tag it as such.

  • Unclear what expected behaviour is for "honest" or "ytterbium".
  • It doesn't respect capitals ("Foo" should turn into "Oofay", and AEIOU are also vowels).
  • It crashes if you pass in the empty string.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文