所以,我需要删除所有包含奇数字母的单词。到目前为止,我已经删除了具有奇数字母的最后一行。我需要如何做它会删除具有奇数字母的行中的每个单词? 文本在数据文件中,我需要将结果打印到另一个没有删除单词的文件。
static void Main(string[] args)
{
Apdorojimas(CFd, CFr, CFv);
}
/// <summary>
/// reads data file and writes the text in result file without deleted words
/// </summary>
/// <param name="duomenųFailas">data file</param>
/// <param name="rezultatųFailas">results file</param>
/// <param name="analizėsFailas">not needed</param>
static void Apdorojimas(string duomenųFailas, string rezultatųFailas, string analizėsFailas)
{
string[] eilutė = File.ReadAllLines(duomenųFailas, Encoding.GetEncoding(1257));
using (var fr = File.CreateText(rezultatųFailas))
{
foreach (string line in eilutė)
{
if (line.Length > 0)
{
string nauja = line;
fr.WriteLine(Ištrinti(nauja));
}
else
for (int i = 0; i < line.Length; i++)
{
if (line.Length == 0)
{
line.Remove(i);
}
}
}
}
}
/// <summary>
/// deletes the word with odd number of letters
/// </summary>
/// <param name="eilutė">Line</param>
/// <returns>line with deleted word</returns>
static string Ištrinti(string eilutė)
{
char[] skyrikliai = { ' ' };
string[] parts = eilutė.Split(skyrikliai, StringSplitOptions.RemoveEmptyEntries);
string eil = eilutė;
foreach (string žodis in parts)
{
for (int i = 0; i < eilutė.Length - 1; i++)
if (žodis.Length % 2 != 0)
{
eil = eilutė.Remove(eilutė.IndexOf(žodis), žodis.Length);
}
}
return eil;
}
}
}
答案 0 :(得分:2)
我将如何做到这一点:
static String Ištrinti(string eilutė)
{
// build a list from the split
List<String> parts = new List<String>(eilutė.Split({' '}, StringSplitOptions.RemoveEmptyEntries));
// iterate the list starting from the bottom
for (Int32 i = parts.Count - 1; i >= 0; --i)
{
// if the length of the current string is odd remove it
if ((parts[i].Length % 2) != 0)
parts.RemoveAt(i);
}
// join the remaining list elements into a single string
return String.Join(" ", parts);
}
使用LINQ
:
static String Ištrinti(string eilutė)
{
// build a list from the split
List<String> parts = new List<String>(eilutė.Split({' '}, StringSplitOptions.RemoveEmptyEntries));
// create another list selecting only the strings with an even length
List<String> partsEven = parts.Where(s => (s.Length % 2) == 0).ToList();
// join the new list elements into a single string
return String.Join(" ", partsEven);
}
答案 1 :(得分:0)
您可以在不使用List
的情况下执行此操作。我假设每行有多个单词,用空格分隔。
基本思想是你为每一行做到这一点:
(last-char-pos - first-char-pos)
C#代码:
using (var output_file = File.CreateText("outputFile.txt"))
{
foreach (var line in File.ReadLines("inputFile.txt"))
{
int start = 0;
while (start < line.Length)
{
// look for start of word
while (start < line.Length && line[start] == ' ')
{
++start;
}
if (start >= line.Length)
{
// no more words on line
break;
}
// now look for end of word
int end = start+1;
while (end < line.Length && line[end] != ' ')
{
++end;
}
int length = end - start;
if ((length % 2) == 0)
{
output_file.WriteLine(line.Substring(start, length));
}
// reposition start for next word
start = end;
}
}
}
这是基本的想法。我没有测试过代码,所以你可能想要这样做。