【问题标题】:Checking to see the char equivalent of my int value检查以查看我的 int 值的 char 等价物
【发布时间】:2018-09-02 23:57:46
【问题描述】:

好吧,我可能没有尽我所能解释它,但我是一个初学者,我想编写一段代码来做到这一点: 你有一个字符串,你需要找到其中的每个元音,并将每个元音在字符串中的位置乘以它在字母表中的位置,然后将所有总和相加 示例: steve:有 2 个元音第一个 e 的位置是 3,它在字母表中的位置是 5。第二个在字母表和字符串中的位置是 5 所以总和是 5*3 + 5*5 = 40 这就是我所做的。不知道现在该做什么或如何处理它

 var vowels = new char[] {'a', 'e', 'i', 'o', 'u', 'y', 'A','E','I', 'O', 'U','Y'};
        var chars = new List<char>();
        List<int> indexes = new List<int>();

        Console.WriteLine("Write something : ");
        var input =  Console.ReadLine();

        int index;
        foreach (var vowel in vowels)
        {
            if (input.Contains(vowel))
            {
                index = input.IndexOf(vowel);
                indexes.Add(index + 1);
                chars.Add(vowel);
            }

        }

【问题讨论】:

  • 你认为input中的第一个字符是位置1还是位置0?
  • ik 它应该是 0 但练习指定它必须是 1 @mjwills

标签: c# char int


【解决方案1】:

考虑这种方法:

using System;
using System.Linq;
using System.Collections.Generic;

namespace Whatever
{
    class Program
    {
        static void Main(string[] args)
        {
            var vowels = new Dictionary<string, int>(5, StringComparer.OrdinalIgnoreCase) { { "a", 1 }, { "e", 5 }, { "i", 9 }, { "o", 15 }, { "u", 21 } };

            Console.WriteLine("Write something : ");
            var input = Console.ReadLine();

            var sum = input.Select((value, index) => new { value, index })
                .Sum(x =>
                    {
                        vowels.TryGetValue(x.value.ToString(), out var multiplier);
                        return (x.index + 1) * multiplier;
                    });

            Console.ReadLine();
        }
    }
}

Select 将原始字符串投影为匿名类型,其中包含char 及其索引。

Sum 检查字符串是否为元音 - 如果是,则将位置 (index + 1) 乘以字母表中的位置(来自 vowels)。

vowels 不区分大小写,因此“A”和“a”被视为相同。

如果编译器抱怨out var,则使用:

int multiplier = 0;
vowels.TryGetValue(x.value.ToString(), out multiplier);
return (x.index + 1) * multiplier;

改为。

【讨论】:

    【解决方案2】:

    我在这里想通了

    for (int i = 0; i < indexes.Count; i++)
            {
                sumofone += indexes[i] * (char.ToUpper(chars[i]) - 64);
            }
    

    【讨论】:

    • 考虑在if 语句的内部 执行此逻辑,以避免需要indexeschars。类似于@Gauravsa 的方法。
    【解决方案3】:

    你可以这样做(参考来自here):

        var vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
    
        Console.WriteLine("Write something : ");
        var input = Console.ReadLine().ToLower();
    
        int total = 0;
        for (int temp = 1; temp <= input.Length; temp++)
        {
            if (vowels.Contains(input[temp - 1]))
            {
                total += temp * (char.ToUpper(input[temp -1]) - 64);
            }
         }
    
         Console.WriteLine("The length is " + total);
    

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多