Поиск предложения с максимальным количеством знаков пунктуации

1 минут

Написать программу, которая считывает текст из файла и выводит на экран предложение, содержащие максимальное количество знаков пунктуации.

Решение на C++:🔗︎

#include <iostream>
#include <fstream>

int main()
{
	// input stream
	std::ifstream fin("input.txt", std::ios::in | std::ios::binary);

	if (!fin) {
		std::cout << "Error opening input.txt" << std::endl;
		return 0;
	}

	// get file size
	fin.seekg(0, std::ios_base::end);
	int file_size = fin.tellg();
	fin.seekg(0, std::ios_base::beg);

	// read file
	char *buf = new char [file_size + 1];
	int punct_max = 0, punct_current = 0, current_start = 0, pos_start = 0, pos_end = 0;

	for (int i = 0; (buf[i] = fin.get()) != EOF; i++) {
		switch (buf[i]) {
			case '\n':
				buf[i] = ' ';
				break;
			case ',':
				punct_current++;
				break;
			case '.': case '?': case '!':
				if (punct_current > punct_max) {
					punct_max = punct_current;

					pos_start = current_start;
					pos_end = i;
				}

				punct_current = 0;
				current_start = i + 1;
				break;
		}
	}

	// print sentence
	bool is_trimmed = false;
	for (int i = pos_start; i <= pos_end; i++) {
		if (!is_trimmed) {
			if (buf[i] == ' ') {
				continue;
			} else {
				is_trimmed = true;
			}
		}

		std::cout << buf[i];
	}

	std::cout << std::endl;
	return 0;
}

Решение на Rust:🔗︎

use std::{fs::File, io::{Read, Result}};

fn main() -> Result<()> {
    let mut file = File::open("input.txt")?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;

    let mut punct_current = 0;
    let mut punct_max = 0;
    let mut current_start = 0;
    let mut pos_start = 0;
    let mut pos_end = 0;

    for (i, ch) in content.chars().enumerate() {
        match ch {
            ',' => {
                punct_current += 1;
            }
            '.' | '?' | '!' => {
                if punct_current > punct_max {
                    punct_max = punct_current;

                    pos_start = current_start;
                    pos_end = i;
                }

                punct_current = 0;
                current_start = i + 1;
            }
            _ => {}
        }
    }

    let result = content
        .get(pos_start..=pos_end)
        .unwrap_or("")
        .replace('\n', " ");

    println!("{}", result.trim());

    Ok(())
}

Входной файл input.txt:🔗︎

The first sentence. Second, huh? Third! Four, three, two, one. The sentence,
ending on the second line.

Результат выполнения программы:🔗︎

Four, three, two, one.