简体   繁体   English

无法将字符串从列表拆分为两部分

[英]Cannot split string from a list to two parts

I'm trying to create an configuration file for my server program. 我正在尝试为服务器程序创建一个配置文件。 I'm reading it line by line and when encounter desired option I'm processing that line. 我正在逐行阅读它,当遇到所需选项时,我正在处理该行。 I have to extract IP written to file, but Visual Studio won't let me. 我必须提取写入文件的IP,但是Visual Studio不允许我这样做。 Here is code of process method: 这是处理方法的代码:

////I'm assuming that file is loading is good...
private int processIp()
{
        String tempIpAddr = "";

        Console.Write("IP");
        for (int i = 0; i < readLines.Count; i++)
        {
            if (readLines[i].Contains("IP"))
            {
                if(readLines[i].Contains(":"))
                {
                    tempIpAddr = readLines.ElementAt(i).Split(':');
                }
            }
        }
        return 0;
 }

I'm getting that error:Error 4 Cannot implicitly convert type 'string[]' to 'string' F:\\DB\\Dropbox\\Repozytoria\\ARDSQL GUI\\Sources\\Configuration.cs 85 38 ARDSQL GUI 我收到该错误:错误4无法将类型'string []'隐式转换为'string'F:\\ DB \\ Dropbox \\ Repozytoria \\ ARDSQL GUI \\ Sources \\ Configuration.cs 85 38 ARDSQL GUI

I tried changing tempIpAddr to array and changing this readLines.ElementAt(i).Split(':'); 我尝试将tempIpAddr更改为array并更改此readLines.ElementAt(i).Split(':'); to this tempIpAddr = readLines[i].Split(':'); 到此tempIpAddr = readLines[i].Split(':');

How to make it work? 如何使其运作?

The result of String.Split() is a string array string[] . String.Split()的结果是一个字符串数组string[]

Adjust your declaration to look like this: 调整您的声明,如下所示:

String[] tempIpAddr;

string.Split() returns an array of strings, and you are trying to assign that to a string variable , which won't work. string.Split()返回一个字符串数组,而您试图将其分配给一个字符串变量,它将不起作用。

If you know that the IP address is always the string segment following the very first ':' on the line, and that there will be nothing following the IP address, you could modify your code thus: 如果您知道 IP地址始终是该行中第一个':'之后的字符串段,并且IP地址后面没有任何内容,则可以修改代码:

tempIpAddr = readLines.ElementAt(i).Split(':')[1]

But trusting your client is a sure-fire way to fail. 但是,信任您的客户是成功的必由之路。 And I would at least do a Trim() after the Split(). 而且我至少会在Split()之后执行Trim()。

(There are a few other problems in your code, but you may already be aware of them: ie you aren't returning the temp IP address or doing anything else with it.) (您的代码中还有其他一些问题,但是您可能已经意识到了:即您不会返回临时IP地址或对其进行任何其他操作。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM