gpt4 book ai didi

C# String.Substring 截取一个Ip Address和一个String

转载 作者:行者123 更新时间:2023-11-30 20:30:01 24 4
gpt4 key购买 nike

以下代码总是会崩溃。输入是这样的: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) Der Index und die Länge müssen sich auf eine Position in der Zeichenfolge beziehen。
Parametername: length
这是我的错误翻译:索引和长度应该在字符串中的某个位置指定。参数:长度 我希望这是有道理的

最佳答案

很明显,分隔符是 那么为什么要使用 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 Address和一个String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com