0

I'm trying to create an application that confronts a string given in input by the user to a series of words written in the file. Each word is written on a different line without spaces between the lines. They look like this:

TEST

WORD

TEST2

And I would need the array to save them each with their own position so that if I used array[1] , I would get "WORD".

I have tried a few different methods but I can't make it work. Now I am trying to use the File.ReadLines command this way:

string[] wordlist;
string file = @"C:\file";
bool check = false;


if(File.Exists(file))
{
   wordlist = File.ReadLines(file).ToArray();
}

for(int i = 0; i < wordlist.Length && check == false; i++)
{
  if(wordInput == wordlist[i])
    check = true;
}

I don't understand if this turns the entire file into one big variable or if it just saves the lines not as strings but as something else

Son of Man
  • 1,213
  • 2
  • 7
  • 27
  • 1
    "if I used array[2] I would get "WORD" - but WORD is the second line you've shown, therefore it would be at index 1... – Jon Skeet Apr 14 '23 at 17:20
  • 3
    You misspelled `Length`. And it should be `&&` in the loop condition. – 001 Apr 14 '23 at 17:24
  • Side note: For simplicity sake you can just use a `break;` statement rather than the "check" boolean flag. Unless if you are using that var in other places for other reasons – Narish Apr 14 '23 at 17:45

1 Answers1

0

So you have wordInput and you want to check if file has such a line. You can query with a help of Linq, Any. Please, note, that in general case you can well have very long file which doesn't fit array (which should be below 2GB):

using System.IO;
using System.Linq;

...

bool check = false;

try {
  if (File.Exists(file))
    check = File
      .ReadLines(file)
      .Any(line => string.Equals(wordInput?.Trim(), 
                                 line, 
                                 StringComparison.OrdinalIgnoreCase));
}
catch (IOException) {
  ;
}

I've added ?.Trim() to wordInput since all the words in file are trimmed ("word is written on a different line without space"), but I am not sure if wordInput has unwanted leading and trailing spaces.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215