Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# - How can I read and find specific information in a txt file and compare it to strings unity

I am trying to make a game similar to scrabble in unity c#. The unity version I am using is 2019.4. I have a txt file which contains 58110 words. I would like to have a unity script which sees if a string is contained in the txt (The string is a word inputted by the player). I have looked up a few tutorials but none have been able to offer what I have been looking for and I am to beginner to try do it on my own (sorry) so what is the best way to do this? (I haven't tried anything so far because the results of the tutorials have not been satisfactory and of course I have no idea how to do it on my own).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming unity has access to these calls. You can just use File.ReadAllines and then convert it to a HashSet, use Contains to do a fast lookup.

var hashSet = File
     .ReadAllLines("SomeFileName")
     .ToHashSet();
   // if you want case insensitivity
   //.ToHashSet(StringComparer.OrdinalIgnoreCase);

if (hashSet .Contains(SomeUserInputedString))
   Debug.Log("You Won");

If unity doesn't have ToHashSet, you can just use its constructor

var hashSet = new HashSet(File.ReadAllLines("SomeFileName")) ;

Additional Resources

File.ReadAllLines Method

Opens a text file, reads all lines of the file into a string array, and then closes the file.

Enumerable.ToHashSet Method

Creates a HashSet<T> from an IEnumerable<T> using the comparer to compare keys.

HashSet.Contains(T) Method

Determines whether a HashSet object contains the specified element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...