Search for a word in a string by letter

Condition:

Write a program that searches in a string entered by the user and displays words starting with a specific letter. The letter is entered by the user.

I know how to perform I / O. Next, as far as I understand, you need to break the words character by character and check all the characters after the space, and if the letter after the space is the same as the specified one, then output all the characters up to the next space. But how to write it all in the code, I I have no idea.

Author: Alexander Semikashev, 2019-06-08

2 answers

I see this program like this:

public static void main(String[] args) {

        System.out.println("Введите строку:");
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();

        System.out.println("Введите букву:");
        String letter = scanner.next();

        Pattern pattern = Pattern.compile("\\p{IsCyrillic}+");
        Matcher matcher = pattern.matcher(line);

        while (matcher.find()) {
            String word = matcher.group();
            if(word.toLowerCase().startsWith(letter))
                System.out.println(word);
        }
    }

1) Scanning two rows with Scanner.
2) Using .split(), we divide the string into words that are entered in the array String[] arrayString (.split() returns an array).
3) Using for-each loop (for (String word : arrayString)), we check each element in the array (since the word can be capitalized - we use .toLowerCase()), whether the word begins with the letter (.startsWith(letter)) that was entered by the user earlier.
4) If such a word found, then we display it on the screen.

 0
Author: Antonio112009, 2019-07-16 23:28:55

It is possible at the primitive level:

    String string = "cat bee dog cow cat dog fly";
    char firstLetter = 'c';
    char[] chars = string.toCharArray();
    String word = "";
    for (int i = 0; i < chars.length - 1; i++) {
        if (chars[i] == ' ' && !word.equals("")) {
            if (word.toCharArray()[0] == firstLetter) {
                System.out.println(word);
            }
            word = "";
            continue;
        }
        word = word.concat(String.valueOf(chars[i]));
    }

Result

cat
cow
cat

Possibly due to the fact that the first letter is entered by the user in the string

if (word.toCharArray()[0] == firstLetter)

You will need to replace it with

if (String.valueOf(word.toCharArray()[0]).equals(firstLetter))

Even better, replace it immediately with

if (word.startsWith(prefix)) //String prefix = "ca";  --> result: cat cat

Then it will check whether the word starts with the entered string, not just the letter.

 0
Author: Dedmikash, 2019-06-08 22:24:34