Created
May 4, 2020 17:53
-
-
Save Zulcom/c71e96a85706d92cb12f92a7e383631f to your computer and use it in GitHub Desktop.
С# - Скопировать в out.txt предложения с фразой искомой в input.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
namespace files | |
{ | |
class Program | |
{ | |
static string prompt(string question) | |
{ | |
Console.WriteLine(question); // пишем запрос в консоль | |
return Console.ReadLine(); // возвращаем ввод от пользователя в переменную | |
} | |
static string processInSentence(string input, string searchStr) | |
{ | |
string[] sentences = input.Split('.'); // разбиваем весь текст в массив строк по точкам и назовём его "массив предложений" | |
return String.Join(".", Array.FindAll(sentences, c => c.Contains(searchStr))); | |
// Найти в массиве предложений все предложения которые содержат searchStr и вернуть результат массивом | |
} | |
static string processWeirdTask(string input, string searchStr) | |
{ | |
int at = 0; | |
int end = input.Length; | |
int start = 0; | |
int count = 0; | |
int lastAddedSentenceEnd = 0; | |
List<string> result = new List<string>(); | |
while ((start <= end) && (at > -1)) | |
{ | |
count = end - start; | |
at = input.IndexOf(searchStr, start, count); // at - начало searchStr внутри input | |
if (at == -1) break; // если -1 значит больше нет найденных подстрок | |
int nearestRightDot = input.IndexOf('.', at + searchStr.Length); // ищем ближайшую далее по тексту начиная с конца найденной фразы | |
if (nearestRightDot == -1) nearestRightDot = input.Length - 1; // если точка не найдена, скорее всего мы достигли конца файла | |
if (lastAddedSentenceEnd < at) | |
{ | |
int nearestLeftDot = input.LastIndexOf('.', at, at - lastAddedSentenceEnd) - 1; // ищем ближайшую точку с момента предыдущего предложения и до новой находки | |
if (nearestLeftDot == -2) | |
{ | |
nearestLeftDot = 0; // если точка не найдена, скорее всего предложение начинается в начале файла | |
} | |
result.Add(input.Substring(nearestLeftDot + 1, nearestRightDot - nearestLeftDot)); // добавляем в массив результатов вразу между точками | |
lastAddedSentenceEnd = nearestRightDot; | |
} | |
start = at + 1; | |
} | |
return String.Join("", result.ToArray()); // склеиваем результаты | |
} | |
static void Main(string[] args) | |
{ | |
var inputFilePath = prompt("Enter input file path:"); | |
var outputFilePath = prompt("Enter output file path:"); | |
var searchStr = prompt("Enter string to search:"); | |
try | |
{ | |
String input = File.ReadAllText(inputFilePath); | |
string output; | |
if (searchStr.Contains('.')) | |
{ | |
output = processWeirdTask(input, searchStr); | |
} | |
else | |
{ | |
output = processInSentence(input, searchStr); | |
} | |
File.WriteAllText(outputFilePath, output); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment