C# String.Substring 剪切出一个 Ip 地址和一个字符串

标签 c# string substring

以下代码总是崩溃。输入是这样的: 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/

相关文章:

c# - 向 Word 添加自定义任务 Pane (不使用 VSTO)

java - 使用 PhotoView 放大后无法达到图像的原始大小

c# - 如何以编程方式访问 Outlook 中共享邮箱的联系人通讯簿

python - 在正则表达式中选择破折号后的单词

c# - 使用 WebAuthenticationCoreManager 进行 Facebook 身份验证的 url 是什么

Python 在文本文件中保存长字符串

Java:如何分割字符串而忽略其他部分

java - 提取小数点后的最后一个数字

iPhone 核心文本 : Find the pixel coordinates of a substring

c++ - 从字符数组中提取字符串