Though there are many ways to do this. However, here is a succinct solution (to ô̖p̖̝̃̉en̺͔͍͌̍̈́ y̯͇̦͌̍͌oũ̠͍̫̀͡r̜̚ m̠̞͑̍i̭̓ṇ̼̍͘d͈̪͍̑̚͝) using a Dictionary
and LINQ.
Since the words are separated by a space, then a simple string.Split
would work fine.
var dict = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
{"Grr", "Lion"},
{"Rawr", "Tiger"},
{"Ssss", "Snake"},
{"Chirp", "Bird"},
};
var animals = Console
.ReadLine()?
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(word => !dict.TryGetValue(word, out var animal) ? "N/A" : animal)
.ToList();
if (animals?.Any() == true)
Console.WriteLine(string.Join(", ", animals));
else
Console.WriteLine("Nothing entered");
Input
grr bob chirp ssss
Output
Lion, N/A, Bird, Snake
Additional Resources
Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.
Dictionary<TKey,TValue>(IEqualityComparer)
The
IEqualityComparer<T>
implementation to use when comparing keys, or null to use the defaultEqualityComparer<T>
for the type of the key.
Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method
Gets the value associated with the specified key.
Projects each element of a sequence into a new form.
Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.
Null-conditional operators ?. and ?[]
Available in C# 6 and later, a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null
Language Integrated Query (LINQ)
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, a query is a first-class language construct, just like classes, methods, events. You write queries against strongly typed collections of objects by using language keywords and familiar operators.
CLICK HERE to find out more related problems solutions.