diff --git a/Lab4.FirstEqualLast/Program.cs b/Lab4.FirstEqualLast/Program.cs index 7ae957b..5f8de20 100644 --- a/Lab4.FirstEqualLast/Program.cs +++ b/Lab4.FirstEqualLast/Program.cs @@ -8,7 +8,7 @@ namespace Lab4.FirstEqualLast public static void Main(string[] args) { const string CFd = "Duomenys.txt"; - char [] punctuation = {' ','.',',','!','?',':',';','(',')','\t'}; + string punctuation = "[\\s,.;:!?()\\-]+"; Console.WriteLine("Sutampančių žodžių {0, 3:d}", TaskUtils.Process(CFd, punctuation)); } } diff --git a/Lab4.FirstEqualLast/TaskUtils.cs b/Lab4.FirstEqualLast/TaskUtils.cs index 52c4993..af0fe1d 100644 --- a/Lab4.FirstEqualLast/TaskUtils.cs +++ b/Lab4.FirstEqualLast/TaskUtils.cs @@ -1,11 +1,41 @@ using System; using System.Collections.Generic; using System.Text; +using System.Text.RegularExpressions; namespace Lab4.FirstEqualLast { public class TaskUtils { + /** Reads file and finds the number of words having same the first and + the last letters. + @param fin – name of data file + @param punctuation – punctuation marks to separate words */ + public static int Process(string fin, string punctuation) + { + string[] lines = File.ReadAllLines(fin, Encoding.UTF8); + int equal = 0; + foreach (string line in lines) + if (line.Length > 0) + equal += FirstEqualLast(line, punctuation); + return equal; + } + + /** Splits line into words and counts the words having same the first + and the last letters. + @param line – string of data + @param punctuation – punctuation marks to separate words */ + private static int FirstEqualLast (string line, string punctuation) + { + string[] parts = Regex.Split(line, punctuation); + int equal = 0; + foreach (string word in parts) + if(word.Length > 0) // empty words at the end of line + if (word[0] == word[word.Length - 1]) + equal++; + return equal; + } + /** Reads file and finds the number of words having same the first and the last letters. @param fin – name of data file @@ -15,8 +45,8 @@ namespace Lab4.FirstEqualLast string[] lines = File.ReadAllLines(fin, Encoding.UTF8); int equal = 0; foreach (string line in lines) - if (line.Length > 0) - equal += FirstEqualLast(line, punctuation); + if (line.Length > 0) + equal += FirstEqualLast(line, punctuation); return equal; }