user8421021
user8421021

Reputation:

remove dot from end of word in array using C#

I have program that reads data from .txt file. I want to read only names that ends with letters "ec". If that name has dot (.) in the end I want to remove it.

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();
    }
}

I am not sure if this is the right way to display name that ends with letter e. Also I have been trying to use something like this

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

I have tried more way but I got lost.

Upvotes: 0

Views: 611

Answers (5)

Andy G
Andy G

Reputation: 19367

To end-up with a collection of those words that end with "ec" or "ec." (as "I want to read only names that..." suggests):

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

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

I suggest extracting these names with a help of regular expressions and 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

Matching, instead of trimming let you het rid of punctuation:

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

After Console.WriteLine(string.Join(Environment.NewLine, words)); we'll get

   ...
   Quebec
   ...

Please notice both ' and , removed. The implementation:

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()));
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

I want the words that end with "ec" an then remove dot if there is one

You're doing the split only once before the loop, instead use:

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;
        }
    }
}

This approach first removes the dot from the end of each string, stores this into a local variable word. Then it checks if this word now EndsWith("ec")(dot already removed). If that's true this new word without dot will replace the old word in the array.

Upvotes: 2

David
David

Reputation: 219037

This will trim the character from the end of the string:

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

But it doesn't modify the string in-place. Rather, like most (all?) string manipulation functions in C#, it returns the new string. You just need to capture that modified value. If you want it to be "in-place" then something like this:

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

Or you could put it into a new variable instead if you like and then use that variable going forward.

Upvotes: 0

Barr J
Barr J

Reputation: 10927

You need to create a variable that the return value will populate:

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

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

Upvotes: 0

Related Questions