I'm trying to get a sum value based on what characters a string contains. The character values are determined by me and are somewhat arbitrary ('A' = 1, 'B' = 4, 'C' = 2, etc.). For example, if string s = "ABC" then int value = 7 because 1 + 4 + 2 = 7. What would be an efficient way to write this in C#?
Right now my code looks like this:
//Declare variables
string name = JOHN
int i = 0;
int nameValue = 0;
string temp = "";
string[] nameArray;
//Convert name to string array so I can use String.Contains() to check what letters are in name
foreach (char c in name)
{
temp += c.ToString();
temp += ".";
}
temp = temp.Remove(temp.Length - 1, 1);
nameArray = temp.Split('.');
//Determine nameValue by iterating through nameArray and checking each string
foreach (string s in nameArray)
{
if (nameArray[i].Contains('A')) { nameValue += 1 }
else if (nameArray[i].Contains('B')) { nameValue += 4 }
else if (nameArray[i].Contains('C')) { nameValue += 2 }
else if (nameArray[i].Contains('D')) { nameValue += 3 }
.
.
.
else if (nameArray[i].Contains('Y')) { nameValue += 7 }
else if (nameArray[i].Contains('Z')) { nameValue += 5 }
i++;
}
Console.WriteLine(nameValue);
I changed the string to a string array because I have names that have repeating letters (i.e. Jill), and I want to give every letter in the name a value. If I used String.Contains() without separating every letter, it would only count repeating letters once, I think.
I feel like there has to be a better way than doing all that string manipulation and using a separate conditional statement for every letter in the alphabet, but I couldn't find anything. Thanks.
Aucun commentaire:
Enregistrer un commentaire