[英]trying to convert a string to a array without having any spaces in the string C#
好的,所以我只是想出了一種如何將8位二進制代碼轉換為數字的方法(或者,我認為),還有什么更好的方法來學習它,那就是編寫一個適合您的程序! 而且我有點被卡住了。 我試圖找出如何將字符串轉換為字符串array [],這樣我就可以遍歷它並將所有內容加在一起,但是我似乎找不到不需要空格或任何內容的東西。 任何人有任何想法嗎? 這是我的代碼。
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
}
}
}
}
}
希望這會幫助你。 String實現IEnumerable接口,該接口將為您提供一個用於枚舉的枚舉器。
Console.WriteLine("Please enter 8 digit binary number");
string input = Console.ReadLine();
foreach (var item in input)
{
Console.WriteLine("Item is {0}", item);
}
開始修復程序:
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
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.