I've tested with numerous strings of different lengths and different numbers of spaces, empty string, null. All of them either produce a substring that matches the requirement (with no leading or trailing spaces), or throws the required exception.
There is one situation where the conditions aren't clear. Consider the following string :
System.out.println(getPartOfString("CodeGym is the best "));
Note that the 4th space is the last character of the string. I am not sure if this is supposed to qualify as a valid string or be considered too short. My current code assumes that "" is not a valid word after the 4th space, and throws an exception. However I have also tried the code without that last call to throw the exception, which prints
"is the best "
and it also doesn't work. In fact the validation doesn't change at all regardless of whether I allow that string to pass or not, so I'm thinking that not only is it not the reason I'm not passing validation, but CodeGym doesn't even care if that string passes or not.package com.codegym.task.task22.task2202;
/*
Find a substring
*/
public class Solution
{
public static void main(String[] args) throws StringTooShortException
{
System.out.println(getPartOfString("CodeGym is the best "));
//System.out.println(getPartOfString("CodeGym is the best place"));
//System.out.println(getPartOfString("CodeGym"));
//System.out.println(getPartOfString(""));
//System.out.println(getPartOfString(null));
}
public static String getPartOfString(String string) throws StringTooShortException
{
if(string == null)
{
throw new StringTooShortException();
}
String output = null;
int firstSpace = string.indexOf(" ");
int fourthSpace = 0;
int spaceCount = 0;
for (int i = 0; i < string.length(); i++)
{
if (string.charAt(i) == ' ')
{
spaceCount++;
}
if (spaceCount == 4)
{
fourthSpace = i;
break;
}
}
if(spaceCount < 4)
{
throw new StringTooShortException();
}
String fifthWord = "";
for (int i = fourthSpace + 1; i < string.length(); i++)
{
if (Character.isLetter(string.charAt(i)))
{
fifthWord += string.charAt(i);
}
else
{
break;
}
}
if(fifthWord.length() == 0)
{
throw new StringTooShortException();
}
output = string.substring(firstSpace + 1, fourthSpace + fifthWord.length() +1);
return output;
}
public static class StringTooShortException extends RuntimeException
{
public StringTooShortException()
{
super();
}
}
}