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 (ie 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.
If you want to map consequent characters (say, 'A'..'Z'
) to integer values, I suggest using array :
using System.Linq;
...
int[] map = new int[] {
//TODO: put corresponding integer values starting from 'A'
4, 2, 3
};
...
s = "ABC";
int sum = s.Sum(c => map[c - 'A']);
In general case, if you want to map arbitrary symbols, you can use dictionary :
using System.Linq;
...
Dictionary<char, int> map = new Dictionary<char, int>() {
//TODO: put all required pairs here
{'A', 4},
{'B', 2},
{'C', 1},
{'#', -123},
};
...
s = "ABC";
// if there's no map (e.g. for '*'), we assume the value being 0
int sum = s.Sum(c => map.TryGetValue(c, out int v) ? v : 0);
you will see that capitol A is 65
string str = "Hi there";
foreach(char c in str.ToUpper())
{
value += ((int)c) - 64;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.