When I input a word like for example hello
it prints this 4 1 3 3 1 = 12
Console.Write("Give a word: ");
string word = Console.ReadLine();
string smallword = word.ToLower();
int sum = 0;
foreach (char letter in smallword)
{
int index = Array.IndexOf(alphabet, letter);
int score = scores[index];
sum = sum score;
string addingEverythingTogether = $" {score} ";
Console.Write(addingEverythingTogether);
}
Console.Write($"= {sum}");
But it should be printing this 4 1 3 3 1 = 12
. The same line but with out the extra " " at the end. How can I remove this last ' '?
CodePudding user response:
When you have your smallword filled something like
var numbers = smallword.Select(c => scores[Array.IndexOf(alphabet, c)]);
Console.WriteLine($"{string.Join(" ", numbers)}= {numbers.Sum()}");
CodePudding user response:
LINQ is your friend:
var word = Console.ReadLine();
var wordScores = word.Select(ch => scores[Array.IndexOf(alphabet, char.ToLower(ch))])
.ToArray();
Console.WriteLine($"{string.Join(" ", wordScores.Cast<object>())} = {wordScores.Sum()}");
LINQ is a great way to flatten loops into more succinct statements. The Select
method will get you all the scores that correspond to the letters in the word. the string.Join
method then does what you specifically asked about, i.e. creates a single string
from multiple values with the specified delimiter between them. The single call to Sum
will add up all the scores in that array.
The Cast
call may be unnecessary but I think that string.Join
doesn't work with value-type lists, so that call boxes each int
value and produces an IEnumerable<object>
, which should work.
CodePudding user response:
You can refactor your code like this and you can use LINQ to help you;
private static readonly Dictionary<char, int> _scores = new Dictionary<char, int>
{
{ 'a', 1 }, { 'b', 3 }, { 'c', 5 }, { 'd', 2 }, { 'e', 1 }, { 'f', 4 }, { 'g', 3 },
{ 'h', 4 }, { 'i', 1 }, { 'j', 4 }, { 'k', 3 }, { 'l', 3 }, { 'm', 3 }, { 'n', 1 },
{ 'o', 1 }, { 'p', 3 }, { 'q', 10 }, { 'r', 2 }, { 's', 2 }, { 't', 2 }, { 'u', 4 },
{ 'v', 4 }, { 'w', 5 }, { 'x', 8 }, { 'y', 8 }, { 'z', 4 }
};
public static void Main()
{
Console.Write("Geef een word: ");
string input = Console.ReadLine().ToLowerInvariant();
var scores = input.Select(c => _scores[c]).ToList();
Console.WriteLine($"{string.Join(" ", scores)} = {scores.Sum()}"); // 4 1 3 3 1 = 12
}
You simply create a dictionary to hold your letters and corresponding scores. Then you just access to the score with just passing the letter. No nede for creating 2 arrays, getting index from the first array and then access to second list's index etc.