c# - 尝试将字符串转换为数组而字符串中没有任何空格 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
}
}
}
}
}
解决方案
要开始修复您的程序:
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
*/
推荐阅读
- python - 如何从python中的字符串中删除这些特殊的ascii字符?
- angular - 角度文本框的动态串联名称
- shared-hosting - 我所有的帖子请求都给我“由于不活动,该页面已过期。请刷新并重试。” 我的共享主机 laravel 5.6 中的错误
- c# - 如何使用代码统一更改轻组件中的烘焙(烘焙类型)?
- xpath - XPath:在匹配条件的第一个元素上停止收集元素
- swift - iTunes Store 操作失败。没有找到合适的申请记录
- image - 错误:在 Octave 4.2.2 中未定义 rgb2gray
- azure - 如何使用具有凭据的 USQL 数据库项目?
- c# - sql中锁资源死锁
- visual-studio - TFS 不会删除本地副本