【问题标题】:Position of Indexes present in a string in C# [duplicate]C#中字符串中存在的索引位置[重复]
【发布时间】:2013-10-04 17:30:38
【问题描述】:

基本上,我正在制作一个包含两个部分的程序

1) 将给定的字符串从 HEX 转换为 BINARY (DID IT)

我遇到问题的部分是 :-

2) 打印 1 在转换后的字符串中的位置 例如,我转换后的字符串是

1011000001001 所以我想打印 1,3,4,10,13(这些是字符串中 1 的位置)

我的代码是:-

private void button1_Click(object sender, EventArgs e)

      {

        string temp = textBox1.Text;
        string binary = ConvertTOBinary(temp);
        //Console.WriteLine(binaryval);

    }

公共字符串 ConvertTOBinary(string temp) {

        string binaryval = "";



        binaryval = Convert.ToString(Convert.ToInt64(temp, 16), 2);
        MessageBox.Show(binaryval);


        var indexes = binaryval
            .Select((c, index) => c == '1' ? index + 1 : 0)
            .Where(indexPlus1 => indexPlus1 > 0);
        var indexesText = string.Join(",", indexes);
        MessageBox.Show(indexes);

        return binaryval;


    }

我收到错误:-

1 'string.Join(string, string[])' 的最佳重载方法匹配有一些无效参数'

2':无法从 'System.Collections.Generic.IEnumerable' 转换为 'string[]'

3 'System.Windows.Forms.MessageBox.Show(string)' 的最佳重载方法匹配有一些无效参数 C:\Documents and Settings\Hamza\My Documents\Visual Studio 2008\Projects\Import-Compare\导入比较\Parser.cs 46 13 导入比较 错误

4 参数“1”:无法从“System.Collections.Generic.IEnumerable”转换为“字符串”

请帮助需要! :(

【问题讨论】:

  • 请使用与上一个问题不同的标题,这样您的问题更有可能因为完全重复而被关闭。
  • 您可能想尝试在所有 LINQ 的末尾添加 ToArray()。或者阅读手册。
  • 它与您之前的问题非常相关。您已经有一个 answer 如果还有什么问题仍然无法正常工作,请在该答案上发表评论,而不是遵循不正确的答案
  • MessageBox.Show(string.Join(",", str.Select((r, i) => new { Value = r, Index = i }).Where(r => r.Value == '1').Select(r => r.Index + 1)));

标签: c# visual-studio-2008 coding-style c#-3.0 c#-2.0


【解决方案1】:

Linq 是一个很棒的东西,但有时以“老派”的方式做事更容易,更重要的是更清晰:

        var test = "1011000001001";
        var answer = new StringBuilder();

        var ix = test.IndexOf('1');
        while (ix > -1) {
            ix = ix + 1;
            answer.AppendFormat("{0},", ix);
            ix = test.IndexOf('1', ix);
            }
        var counts = answer.ToString().TrimEnd(new char[] { ',' });
        Console.WriteLine(counts);

请记住,有一天您可能不得不返回该代码并弄清楚它的作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多