I tried different ways to define "the word that follows the 4th space", with space or punctuation marks etc. But none can be verified. Has anyone solved this?
package com.codegym.task.task22.task2202;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
Find a substring
*/
public class Solution {
public static void main(String[] args) {
System.out.println(getPartOfString("CodeGym is the best place!"));
}
public static String getPartOfString(String string) throws StringTooShortException {
if (string == null) throw new StringTooShortException();
String s = string;
int start = s.indexOf(" ") + 1;
int add = start;
int end = start;
for (int i = 0; i < 4; i++) {
s = s.substring(add);
if (add == 0) throw new StringTooShortException();
else {
add = s.indexOf(" ") + 1;
end += add;
}
}
end -= add;
if (s.matches("\\w+\\W+.*")) {
Pattern pattern = Pattern.compile("\\W+");
Matcher matcher = pattern.matcher(s);
if (matcher.find())
end += matcher.start();
}else end = string.length();
return string.substring(start, end);
}
public static class StringTooShortException extends RuntimeException{
}
}