Как найти самое длинное и самое короткое предложение в строке

230
26 мая 2019, 12:10

Как найти самое длинное и самое короткое предложение в строке s без использования split(), ArrayList и так далее. В данном коде я уже нашел количество слов, среднее количество слов, самое длинное и самое короткое слово, количество предложений и среднее число слов в предложении. Заранее спасибо.

Вот мой код на данный момент:

class stringManipulation{
public static void main(String[] args){
    String s = "A stray Lamb stood drinking early one morning on the bank of a woodland stream."+
    " That very same morning a hungry Wolf came by farther up the stream, hunting for something to"+
    " eat. He soon got his eyes on the Lamb. As a rule Mr. Wolf snapped up such delicious morsels "+
    "without making any bones about it, but this Lamb looked so very helpless and innocent that the "+
    "Wolf felt he ought to have some kind of an excuse for taking its life. \"How dare you paddle "+
    "around in my stream and stir up all the mud!\" he shouted fiercely. \"You deserve to be "+
    "punished severely for your rashness!\" \"But, your highness,\" replied the trembling Lamb,"+
    "\"do not be angry! I cannot possibly muddy the water you are drinking up there. Remember, "+
    "you are upstream and I am downstream.\" \"You do muddy it!\" retorted the Wolf savagely. \""+
    "And besides, I have heard that you told lies about me last year!\" \"How could I have "+
    "done so?\" pleaded the Lamb. \"I wasn't born until this year.\" \"If it wasn't you, "+
    "it was your brother!\" \"I have no brothers.\" \"Well, then,\" snarled the Wolf, \"It "+
    "was someone in your family anyway. But no matter who it was, I do not intend to be "+
    "talked out of my breakfast.\" And without more words the Wolf seized the poor Lamb "+
    "and carried her off to the forest.";

    int counter = 0;
    double spaces = 1;
    int stringLength = s.length();
    String store = "";
    String longestWord = "";
    String shortestWord = "";
    int l = 0;
    /*String symbols = ".,?!";*/
    int sentences = 0;
    String longestSentence = "";
    while(counter < s.length()){
        char c = s.charAt(counter);
        if(c == '.'){
            sentences++;
        }
        if(c == ' '){
            spaces++;
        }
        if(c != ' '){
            store = store + c;
        } 
        else{
            if(store.length() > longestWord.length()){
                longestWord = store;
            }
            l = store.length();
            if(l < stringLength){
                stringLength = l;
                shortestWord = store;
            }
            store = "";
        } 
        counter++;
    }
    double average = ((counter - spaces) / spaces);
    System.out.println(spaces + " words in a string");
    System.out.println(average + " is the average word length");
    System.out.println((counter-spaces) + " characters without spaces");
    System.out.println("Longest word: " + longestWord.length() + " character(s) " + "( " + longestWord + " )");
    System.out.println("Shortest word: " + shortestWord.length() + " character(s) " + "( " + shortestWord + " )");
    System.out.println(sentences + " sentences");
    System.out.println("The average sentence length: " + spaces / sentences + " words");
    /*System.out.println("Longest sentence: " + longestSentence);*/
}

}

Answer 1
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        String s = "A stray Lamb stood drinking early one morning on the bank of a woodland stream." +
                " That very same morning a hungry Wolf came by farther up the stream, hunting for something to" +
                " eat. He soon got his eyes on the Lamb. As a rule Mr. Wolf snapped up such delicious morsels " +
                "without making any bones about it, but this Lamb looked so very helpless and innocent that the " +
                "Wolf felt he ought to have some kind of an excuse for taking its life. \"How dare you paddle " +
                "around in my stream and stir up all the mud!\" he shouted fiercely. \"You deserve to be " +
                "punished severely for your rashness!\" \"But, your highness,\" replied the trembling Lamb," +
                "\"do not be angry! I cannot possibly muddy the water you are drinking up there. Remember, " +
                "you are upstream and I am downstream.\" \"You do muddy it!\" retorted the Wolf savagely. \"" +
                "And besides, I have heard that you told lies about me last year!\" \"How could I have " +
                "done so?\" pleaded the Lamb. \"I wasn't born until this year.\" \"If it wasn't you, " +
                "it was your brother!\" \"I have no brothers.\" \"Well, then,\" snarled the Wolf, \"It " +
                "was someone in your family anyway. But no matter who it was, I do not intend to be " +
                "talked out of my breakfast.\" And without more words the Wolf seized the poor Lamb " +
                "and carried her off to the forest.";
        List<String> sentences = new ArrayList<>();
        StringBuilder sentence = new StringBuilder();
        for (char c : s.toCharArray()) {
            sentence.append(c);
            if (c == '.') {
                sentences.add(sentence.toString());
                sentence = new StringBuilder();
            }
        }
        String min = sentences.stream().min(Comparator.comparingInt(String::length)).get();
        System.out.println(min);
        String max = sentences.stream().max(Comparator.comparingInt(String::length)).get();
        System.out.println(max);
    }
}
READ ALSO
JasperReports. Конвертация строкового параметра в массив

JasperReports. Конвертация строкового параметра в массив

Использую community версию JasperReportsВнутри отчета конструкция $X{IN,db_field,parameter}

142
Квадратная картинка на CSS

Квадратная картинка на CSS

Как сделать на CSS квадратную картинку? Тоесть имеется несколько картинок, одна 500x100, другая 100x500 обе картинки выводятся параметром width:30%; мне...

281
Формат даты с часовым поясом в moment.js

Формат даты с часовым поясом в moment.js

У меня есть дата в формате "Fri, 30 Nov 2018 16:00:00 -0500"Мне нужно ее отформатировать как "MM/DD/YYYY HH:mm A"

159
Owl Carousel 2 - не изменяется размер owl-stage

Owl Carousel 2 - не изменяется размер owl-stage

Такая проблема: Я подключил Owl-Carousel успешно на сайтОн у меня установлен во весь экран компьютера (w:100%; h:100%), но когда я открываю боковое меню...

171