подскажите почему? счётчик правильно считает пробелы и выводит между 1и 4 пробелом
package com.javarush.task.task22.task2202;
/*
Найти подстроку
*/
public class Solution {
public static void main(String[] args) throws TooShortStringException {
System.out.println(getPartOfString("JavaRush - лучший сервис обучения Java."));
System.out.println(getPartOfString("Амиго и Диего лучшие друзья!"));
}
public static String getPartOfString(String string) throws TooShortStringException {
TooShortStringException tooShortStringException = new TooShortStringException();
if(string==null) throw tooShortStringException;
try {
//неправильное решение
/*
int countspace = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == '\u0020') {
countspace++;
}
}
// System.out.println(countspace);
if (countspace < 4) {
throw tooShortStringException;
}
// System.out.println(string.indexOf('\u0020'));
int firstindex = string.indexOf('\u0020');
//int secondtindex = string.indexOf(firstindex+1,'\u0020');
//int therdindex = string.indexOf(secondtindex+1,'\u0020');
int lasttindex = string.lastIndexOf('\u0020');
return string.substring(firstindex + 1, lasttindex);
*/
char[]mass=string.toCharArray();
int count=0;
int first=0;
int fourths=0;
for (int i = 0; i <mass.length ; i++) {
//System.out.println(mass[i]);
if (mass[i]=='\u0020')
count++;
if (count==1){
first=i;
}
if (count==4){
fourths=i;
}
}
if (count < 4) {
throw tooShortStringException;
}
//System.out.println(count);
//System.out.println(firs);
//System.out.println(fourths);
return string.substring(first,fourths+1);
}
catch(Exception e){
throw tooShortStringException;
}
}
public static class TooShortStringException extends RuntimeException {
}
}