使用C#从数组中的单词末尾删除点

时间:2017-12-18 13:39:31

标签: c#

我有从.txt文件中读取数据的程序。我想只读取以字母"ec"结尾的名字。如果该名称最后有点(。)我想删除它。

public static void Main(string[] args)
{
    StreamReader sr = new StreamReader("../../file.txt");

    string data = sr.ReadLine();
    string[] words = sr.ReadToEnd().Split(' ');

    while(data != null){

        for (int i = 0; i < words.Length; i++){

            if (words[i].Contains("ec")){

                Console.WriteLine(words[i]);
            }
        }
        data = sr.ReadLine();
    }
}

我不确定这是否是显示以字母e结尾的名称的正确方法。 我也一直试图使用这样的东西

if (words[i].EndsWith('.')) 
{       
    words[i].TrimEnd('.');
    Console.WriteLine(words[i]);
}

我尝试过更多方法,但我迷路了。

5 个答案:

答案 0 :(得分:2)

  

我想要的结果是&#34; ec&#34;如果有一个

,则删除点

您在循环之前只进行了一次拆分,而是使用:

assessment-1

此方法首先从每个字符串的末尾删除点,将其存储到局部变量StreamReader sr = new StreamReader("../../file.txt"); string line; while((line = sr.ReadLine()) != null) { string[] words = line.Split(' '); for (int i = 0; i < words.Length; i++) { string word = words[i].TrimEnd('.'); if (word.EndsWith("ec")) { words[i] = word; } } } 中。然后它检查这个单词现在word(点已被删除)。如果这是真的,这个没有点的新单词将替换数组中的旧单词。

答案 1 :(得分:0)

您需要创建一个返回值将填充的变量:

if (words[i].EndsWith('.')) {

        string dotlessWord = words[i].TrimEnd('.');
        Console.WriteLine(dotlessWord);
    }

答案 2 :(得分:0)

这将修剪字符串末尾的字符:

words[i].TrimEnd('.');

但它不会就地修改字符串。相反,像C#中的大多数(全部?)字符串操作函数一样,它返回新字符串。您只需捕获该修改后的值即可。如果你想让它“就地”,那就像这样:

words[i] = words[i].TrimEnd('.');

或者你可以把它放到一个新变量中,如果你愿意,然后再使用那个变量。

答案 3 :(得分:0)

我建议在正则表达式 Linq 的帮助下提取这些名称:

using System.Linq;
using System.Text.RegularExpressions;

...

string[] words = File
  .ReadLines("../../file.txt")      
  .SelectMany(line => Regex         // In each line of the file
     .Matches(line, @"\b\w*ec\b")   // extract words which end at "ec"
     .OfType<Match>()
     .Select(match => match.Value))
  .ToArray();                       // if you want array as a final result

匹配,而不是修剪让你摆脱标点符号:

   ...
  'Quebec', we want the name only;
   ...

Console.WriteLine(string.Join(Environment.NewLine, words));之后我们

   ...
   Quebec
   ...

请注意已移除',。实施:

public static void Main(string[] args) {
  Console.WriteLines(string.Join(Environment.NewLine, File
    .ReadLines("../../file.txt")      
    .SelectMany(line => Regex         
       .Matches(line, @"\b\w*ec\b")   
       .OfType<Match>()
       .Select(match => match.Value))
    .ToArray()));
}

答案 4 :(得分:0)

最后收集以“ec”或“ec”结尾的单词。 (因为“我只想阅读......的名字”):

string[] origWords = new [] { "here", "be", "words", "fooec", "barec." };

List<string> ecs = new List<string>();

foreach (string word in origWords) {
    if (word.EndsWith("ec") || word.EndsWith("ec.")) {
        ecs.Add(word.TrimEnd('.'));
    }
}
foreach (string word in ecs) {
    Console.WriteLine(word);
}
// fooec
// barec