读入一个句子,然后打印出仅包含同一字母连续重复3次或更多次的单词。

huangapple go评论63阅读模式
英文:

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

问题

public class Triplets2 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("write a sentence");
        String in = input.nextLine();

        String[] sentence = in.split(" ");

        for (int i = 0; i < sentence.length; i++) {

            char[] word = sentence[i].toCharArray();
            int counter = 0;

            for (int s = 0; s < word.length; s++) {

                char letter = word[s];

                for (int x = 0; x < word.length; x++) {

                    if (letter == word[x]) {
                        counter++;
                    } else {
                        counter = 0;
                    }
                }
            }
            if (counter >= 3) {
                System.out.print(sentence[i] + ",  ");
            }
        }
    }
}
英文:

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan

public class Triplets2 {

public static void main(String[] args) {

	Scanner input = new Scanner(System.in);
	System.out.println(&quot;write a sentence&quot;);
	String in = input.nextLine();
	
	String [] sentence = in.split(&quot; &quot;);
	
	for (int i = 0; i &lt; sentence.length; i++) {
		
		char [] word = sentence[i].toCharArray();
		int counter =0;
		
		for (int s = 0; s &lt; word.length; s++) {
			
			char letter = word
展开收缩
; for (int x = 0; x&lt;word.length; x++) { if (letter == word[x]) { counter++; } else { counter = 0; } } } if (counter &gt;=3) { System.out.print(sentence[i] + &quot;, &quot;); } } }

the program instead just repeats nothing.

答案1

得分: 1

你的代码几乎是正确的,唯一的逻辑错误是在内部循环中,一旦找到不同的字母,你就会重置计数器变量:

if (letter == word[x]) {
    counter++;
} else {
    counter = 0;
}

因此,当你遍历像"raaan"这样的单词时,当到达字符串的末尾时,计数器将被重置,因为只有一个"n"。这意味着你只能检测到在单词末尾有3个连续字母的单词(如"Hooo")。

解决方案很简单:
一旦你在单词中找到了3个连续的字母,你可以停止迭代并检查单词的剩余部分。此时,你已经知道它符合你的条件:

if (letter == word[x]) {
    counter++;
    if (counter >= 3) break; // 找到3个字母后停止内部循环的检查
} else {
    counter = 0;
}
英文:

Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:

if (letter == word[x]) {
    counter++;
} else {
    counter = 0;
}

So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").

The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:

if (letter == word[x]) {
    counter++;
    if(counter &gt;= 3) break; // stop inner loop checking once we found 3 letters
} else {
    counter = 0;
}

答案2

得分: 0

好的,以下是翻译的内容:

嗯,如果你只是想找一个更简短的方法来做这个,那么可以尝试以下方法:

  • 首先,在一个或多个空白字符上拆分句子(无论如何都应该这样做)。
  • 对数组进行流处理,并对单个字符进行过滤,然后通过捕获组的反向引用来过滤相同的两个字符(有关此内容,请参阅正则表达式)。
  • 然后将它们打印出来。
String str =
		"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";

Arrays.stream(str.split("\\s+"))
		.filter(s -> s.matches(".*(.)\\.*"))
		.forEach(System.out::println);

输出结果

Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
英文:

Well, if you're just looking for a shorter version of doing this then try this.

  • first, split the sentence on one or more white space characters (you should be doing that regardless).
  • stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
  • And print them.
String str =
		&quot;Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers&quot;;

Arrays.stream(str.split(&quot;\\s+&quot;))
		.filter(s -&gt; s.matches(&quot;.*(.)\\.*&quot;))
		.forEach(System.out::println);

Prints

Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
		

</details>



# 答案3
**得分**: 0

允许我提出一个与你的略有不同且不使用计数器的解决方案。
```java
Scanner input = new Scanner(System.in);
System.out.println("输入一句话:");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
    char[] word = sentence[i].toCharArray();
    for (int s = 0; s < word.length - 2; s++) {
        if (word
展开收缩
== word
展开收缩
&& word
展开收缩
== word
展开收缩
) { System.out.print(sentence[i] + ", "); break; } } }

检查当前单词中的当前字母是否与下一个字母和下下个字母相同。如果条件成立,则打印当前单词并继续处理句子中的下一个单词。

英文:

Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.

Scanner input = new Scanner(System.in);
System.out.println(&quot;write a sentence&quot;);
String in = input.nextLine();
String[] sentence = in.split(&quot; &quot;);
for (int i = 0; i &lt; sentence.length; i++) {
    char[] word = sentence[i].toCharArray();
    for (int s = 0; s &lt; word.length - 2; s++) {
        if (word[s] == word[s + 1] &amp;&amp; word[s] == word[s + 2]) {
            System.out.print(sentence[i] + &quot;,  &quot;);
            break;
        }
    }
}

Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.

答案4

得分: 0

因为你要寻找连续的字母,所以你需要从字符 i 开始,然后比较字符 i 处的字符与 i+1 处的字符,以及 i+2 处的字符。如果它们都相等,那么就有一个匹配,并且可以继续。

你可以简化整个函数,如下所示:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("写一个句子");
  String in = input.nextLine();

  List<String> tripleLetter = new ArrayList<>();
  for (String s : in.split(" ")) {
    char[] word = s.toCharArray();
    for (int i = 0; i < word.length - 2; i++) {
      if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
        tripleLetter.add(s);
        break;
      }
    }
  }

  System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
英文:

Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.

You can simplify the whole function such as:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println(&quot;write a sentence&quot;);
  String in = input.nextLine();

  List&lt;String&gt; tripleLetter = new ArrayList&lt;&gt;();
  for (String s : in.split(&quot; &quot;)) {
    char[] word = s.toCharArray();
    for (int i = 0; i &lt; word.length - 2; i++) {
      if ((word[i] == word[i+1]) &amp;&amp; (word[i] == word[i+2])) {
        tripleLetter.add(s);
        break;
      }
    }
  }

  System.out.println(tripleLetter.stream().collect(Collectors.joining(&quot;, &quot;)));
}

huangapple
  • 本文由 发表于 2020年9月17日 00:15:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63924123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定