以下代码总是崩溃。输入是这样的:
String 1
是一个 IpAddress
(192.168.187.815
) string 2
应该是一个端口,因此整个输入是192.168.187.815,2332
。应删除 ipAddress(string 1
)和端口(string 2
)的代码如下所示:
Console.Write("String1,String2>");
string both = Console.ReadLine();
string string1 = both.Substring(0,both.IndexOf(","));
Console.WriteLine(string1.Length);
string string2 = both.Substring( string1.Length , both.Length - 1);
Console.WriteLine(string1);
Console.WriteLine(string2);
Console.Read();
有人知道为什么它不起作用吗?
我被要求异常(exception),所以就在这里。
有一个小问题,我来自德国,但德语是个异常(exception)。
我尝试用谷歌翻译器翻译它,但我想我们都知道它是垃圾。这里是原始的德语异常(exception) Der Index und die Länge müssen sich auf eine Position in der Zeichenfolge beziehen。参数名称:长度
这是我的错误翻译:索引和长度应该在字符串中的某个位置指定。参数:长度
我希望这是有意义的
最佳答案
很明显,分隔符是 ,
那么为什么要使用 Substring
让事情变得复杂,为什么不继续使用 Split
,如下所示:
string[] inputParams= both.Split(',');
string ipAddress = inputParams[0];
string portNumber =inputParams[1];
- 其实是
String.Substring()
的第二个参数方法 代表字符数(不是最后一个索引 想法)。 如果您再次希望继续使用
Substring
,您可以尝试如下操作:string ipAddress = both.Substring(0,both.IndexOf(",")); string portNumber =both.Substring(both.IndexOf(",")+1)
但对于这种情况,第一个仍然是最好的
关于C# String.Substring 剪切出一个 Ip 地址和一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436113/