✅ Split Lines into Array Elements
I've got a list of common English words in the format
And so forth. How can I split this into an array of format `string[] arr = {"word1", "word2", "word3", "word4"}.
I imagine this would be done with .Split() but it's not working for me.
21 Replies
When you say it's in that format, you mean it's a load of words, 1 per line, in some file and you're reading them in?
what have u tried, what error did u encounter?
.Split definitely works u are probably using it wrong
By default
Split
uses a whitespace as a delimiter. Pass Environment.NewLine
as an argument
Assuming each word is split by a new lineEnvironment.NewLine
is usually not enough as different operating systems/applications/user settings can affect the actual new line sequenceAdiZ
REPL Result: Failure
Exception: CompilationErrorException
Compile: 699.045ms | Execution: 0.000ms | React with ❌ to remove this embed.
AdiZ
REPL Result: Failure
Exception: CompilationErrorException
Compile: 501.971ms | Execution: 0.000ms | React with ❌ to remove this embed.
AdiZ
REPL Result: Success
Console Output
Compile: 611.380ms | Execution: 47.155ms | React with ❌ to remove this embed.
Oh
My bad guys.
ngl i didnt know it splits on newlines by default
If you are reading this from a file, btw, there's a handy existing method you can use that will handle this for you.
File.ReadLinesAsync(string path)
returns an async enumerable of strings, 1 per line
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-7.0File.ReadLinesAsync Method (System.IO)
Asynchronously reads the lines of a file.
You will want to use
await foreach
for the IAsyncEnumerable it returns, if you dont want to dig into learning how to use await foreach
though you can use the synchronous version of the method, File.ReadLines(string path)
triple quotes for multiline string literals, fyi
TheRanger
REPL Result: Success
Console Output
Compile: 614.818ms | Execution: 91.826ms | React with ❌ to remove this embed.
or that
wait why """ exists if @ exists? 🤔
triple quote version is a lot nicer when you have indentation
because it aligns the "base" indentation of the string with the indentation of the end
"""
Jimmacle
REPL Result: Success
Console Output
Compile: 511.960ms | Execution: 81.608ms | React with ❌ to remove this embed.
TheRanger
REPL Result: Success
Console Output
Compile: 564.989ms | Execution: 38.691ms | React with ❌ to remove this embed.
ah
well, thats just partially correct
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.line breaks just are whitespaces as well, just like space and tab