在C#中添加数组的字符[关闭]

问题描述 投票:-5回答:1

我想做一个简单的爱情计算器。我已预先定义了所有字符值,如a = 1,b = 2和all。但问题是我不知道如何计算长度并逐个添加所有字符。

c# visual-studio-2013
1个回答
1
投票

如果a = 1,b = 2,...,z = 26,你可以做什么的简单例子

string name = "Amélie Benoît Françoise Ågot Annbjørg";

// We transform letters with diacritics to "pure" letters (é->e, ç ->c...)
string normalized = name.Normalize(NormalizationForm.FormD);
var onlyLetters = normalized.Where(x => x >= 'A' && x <= 'Z' || x >= 'a' && x <= 'z');

// Note that the ø of Annbjørg will be stripped :-(
string strippedName = new string(onlyLetters.ToArray());
Console.WriteLine("Calculating for {0}", strippedName);

int sum = 0;

foreach (char ch in onlyLetters)
{
    char ch2 = char.ToUpper(ch);

    // char have a value... 'A' == 65, 'B' == 66 and so on,
    sum += ch2 - 'A' + 1;
}

// Done

请注意,此代码在Turky中将以不完美的方式工作,因为它们具有4 i :-)甚至存在具有ø的挪威名称的问题,而没有说出不使用“欧洲”字母的名称:-)

完整的例子:http://ideone.com/ZHHU4G

您可以使用此方法替换Normalize方法调用(应与Windows应用商店兼容):

public enum NORM_FORM
{
    NormalizationOther = 0,
    NormalizationC = 0x1,
    NormalizationD = 0x2,
    NormalizationKC = 0x5,
    NormalizationKD = 0x6
};

[DllImport("Normaliz.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
public static extern int NormalizeString(NORM_FORM NormForm,
    string lpSrcString,
    int cwSrcLength,
    StringBuilder lpDstString,
    int cwDstLength);

public static string NormalizeString(string unnormalized, NORM_FORM form)
{
    if (unnormalized == string.Empty)
    {
        return unnormalized;
    }

    int bufferSize = NormalizeString(form, unnormalized, unnormalized.Length, null, 0);

    if (bufferSize <= 0)
    {
        throw new Exception(string.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
    }

    var sb = new StringBuilder(bufferSize);

    int result = NormalizeString(form, unnormalized, unnormalized.Length, sb, bufferSize);

    if (result <= 0)
    {
        throw new Exception(string.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
    }

    return sb.ToString();
}

string normalized = NormalizeString(name, NORM_FORM.NormalizationD);
© www.soinside.com 2019 - 2024. All rights reserved.