Question:
One whole line is entered. It is necessary to output those words of the given string that begin with a letter from the interval from a to h.
A word is a collection of letters and symbols from space to space. Words can be in either upper or lower case.
It is necessary to output words each time from a new line.
Пример
Ввод: It becomes dark very fast here
Вывод: becomes
dark
fast
here
It seems that, as I understand it, first you need to translate the string into an array of strings using a regular expression, and then you need a cycle in which, sorting through the strings in the array, using charAt (), you need to get the first letter, which is already checked for validity to the condition and if everything ok – output. That's just the cycle and I can’t think of it … tell me how best to do it?
public class TestClass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String[] strings = s.split(" ");
System.out.println(Arrays.toString(strings));
// вероятно, здесь должен быть цикл
}
}
Answer:
for(String str : strings)
if(str.matches("^[a-h]\\w*"))
System.out.println(str);
If you want to include words ending in 's
along with one word that comes immediately after the above:
String s = "dark's ana here come shot";
Pattern pattern = Pattern.compile("(?<=^| )(\\w+'s )?[a-h]\\w*(?= |$)");
Matcher matcher = pattern.matcher(s);
while(matcher.find())
System.out.println(matcher.group());