代码之家  ›  专栏  ›  技术社区  ›  Developer

如何将数字添加到自己的索引[已关闭]

c#
  •  1
  • Developer  · 技术社区  · 15 年前

      string s"1234567";
    

    为此,每个字符串的索引将为0、1、2、3、4等

    所以输出应该是1,3,5

    2 回复  |  直到 15 年前
        1
  •  4
  •   Marc Gravell    15 年前
    string s = string.Join(",", valueString.Select(
         (c, i) => (i + (int)(c-'0')) % 10));
    

    或在2.0中:

    string[] result = new string[valueString.Length];
    for(int i = 0; i < result.Length ; i++) result[i] =
             ((i + (int)(valueString[i] - '0')) % 10).ToString();
    string s = string.Join(",", result);
    
        2
  •  4
  •   CodesInChaos    15 年前
    IEnumerable<int> IndexDigitSum(string s)
    {
        for(int i=0;i<s.Length;i++)
        {
          int digit=s[i]-'0';
          if(digit<0||digit>9)
             throw new FormatException("Invalid Digit "+s[i]);
          yield return (digit+i)%10;
        }
    }
    

    在.net 2.0中,可以通过添加到本地数组来替换yield return:

    int[] IndexDigitSum(string s)
    {
        int[] result=new int[s.Length];
    
        for(int i=0;i<s.Length;i++)
        {
          int digit=s[i]-'0';
          if(digit<0||digit>9)
             throw new FormatException("Invalid Digit "+s[i]);
          result[i]=(digit+i)%10;
        }
        return result;
    }
    

    或者如果你想让他们具体化:

    string IndexDigitSum(string s)
    {
        string[] parts=new string[s.Length];
    
        for(int i=0;i<s.Length;i++)
        {
          int digit=s[i]-'0';
          if(digit<0||digit>9)
             throw new FormatException("Invalid Digit "+s[i]);
          parts[i]=((digit+i)%10).ToString();
        }
        return string.Join(",", parts);
    }