亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請大佬幫看一下C#里的SubString();,謝謝!

請大佬幫看一下C#里的SubString();,謝謝!

智慧大石 2021-10-12 14:11:24
static void Main(string[] args){string str1 = Console.ReadLine();string str2 = "";byte[] byt=new byte[100];byt = Encoding.Unicode.GetBytes(str1);str2 = Encoding.Unicode.GetString(byt).Substring (0,byt.Length );Console.Write(str2);Console.ReadLine();}這里出現未處理 System.ArgumentOutOfRangeExceptionMessage="索引和長度必須引用該字符串內的位置。\r\n參數名: length"Source="mscorlib"ParamName="length"StackTrace:在 System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)在 System.String.Substring(Int32 startIndex, Int32 length)在 ConsoleApplication15.Program.Main(String[] args) 位置 E:\chen\Visual Studio 2008\Projects\文件\ConsoleApplication15\ConsoleApplication15\Program.cs:行號 17在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)在 System.Threading.ThreadHelper.ThreadStart()InnerException:請問是怎么回事?
查看完整描述

2 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

string str1 = "dsfadfasdfasdfasdfasdfasdfasdfasdf";
string str2 = "";
byte[] byt = new byte[100];
byt = Encoding.Unicode.GetBytes(str1);

str2 = Encoding.Unicode.GetString(byt).Substring(0, byt.Length);
Console.Write(str2);
Console.ReadLine();
上邊是我假設的,此時假設 str1為 "dsfadfasdfasdfasdfasdfasdfasdfasdf"
雖然你定義了 byte[] byt = new byte[100];
但是GetBytes在生成字節序列的時候,填充了數組的前68個,后邊的都是空的,
這樣解碼為str2的時候他的dsfadfasdfasdfasdfasdfasdfasdfasdf的長度還是原來的長度,但是你的byt.Length是100,這樣就造成了越界了,肯定會報錯的 ,
建議你數組可以使用arraylist可變長數組,

查看完整回答
反對 回復 2021-10-16
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

byt的長度是str1轉換字節后的長度,并不是str1的長度,所以可能會引起越界
起始位置和長度要根據str1.length來斟酌

查看完整回答
反對 回復 2021-10-16
  • 2 回答
  • 0 關注
  • 352 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號