首页 > 解决方案 > 尝试将字符串转换为数组而字符串中没有任何空格 C#

问题描述

好的,所以我只是想出了如何将 8 位二进制代码转换为数字(或者我认为),然后通过制作一个为您执行此操作的程序来学习它有什么更好的方法!好吧,我有点卡住了。我试图弄清楚如何将字符串转换为字符串数组 [],这样我就可以遍历它并将所有内容添加在一起,但我似乎无法在不需要空格或任何东西的情况下找到类似的东西。有人有什么想法吗?这是我的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace binary_to_number
{
    class Program
    {
        static int GetAddition(int place)
        {
            switch(place) // goes through the switch until if finds witch place the binary is in 
            {
                case 1:
                    return 128;
                case 2:
                    return 64;
                case 3: return 32;
                case 4: return 16;
                case 5: return 8;
                case 6: return 4;
                case 7: return 2;
                case 8: return 1;
                default: return 0;


            }

        }

        static int ToInt(string input)
        {
            string[] binary = input.Split(); // right here is where im stuck 
            int thenumber = 0; // this is the number it adds to
            for(int i = 0;i < 9;i++)
            {
                Console.WriteLine(binary[i]);
            }
            return thenumber;
        }


        static void Main(string[] args)
        {

            while (true)
            {
                Console.WriteLine("Please put in a 8-digit binary");
                string input = Console.ReadLine();
                if (input.Length < 9) // binary has 8 digits plus the null at the end of each string so if its 
                { // not binary

                    Console.WriteLine(ToInt(input)); // function converts the input into binary
                }

            }



        }


    }
}

标签: c#

解决方案


要开始修复您的程序:

string[] binary = input.Split(); // right here is where im stuck

应该

char[] binary = input.ToCharArray();

for (int i = 0; i < 9; i++)应该for (int i = 0; i < 8; i++)或更好for (int i = 0; i < binary.Length; i++)


更好的方法?

您可以使用Convert该类为自己节省大量代码。

while (true)
{
    Console.WriteLine("Please put a value as binary");
    string input = Console.ReadLine();
    var number = Convert.ToUInt16(input, 2);

    Console.WriteLine($"input:{input}, value: {number}, as binary: {Convert.ToString(number, 2)}");
}
/*
Please put a value as binary
1
input:1, value: 1, as binary: 1

Please put a value as binary
11
input:11, value: 3, as binary: 11

Please put a value as binary
10000001
input:10000001, value: 129, as binary: 10000001
*/

推荐阅读