开发者

Remove characters from server names

In my code, I explicitly specify server names, but I want to implicitly specify server names. Hence, I would like code to take server names implicitely & remove \\ & \n in them.

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "开发者_开发知识库/C net view";
char[] delimiterChars = { '\\' };
string input = "\\st1\n,\\st10\n,\\st4\n,\\st5";
List<string> serverNames = input.Split(',').ToList();
Console.WriteLine(input);
Console.ReadLine();


I don't understand what you're saying about "dynamic arrays", but I think I get what you're trying to do. Here's some code that will split your input and return a list of all the elements without a leading \\ or trailing \n:

List<string> serverNames = input.Split(',')
                                .Select(s => {
                                    if (s.StartsWith(@"\\"))
                                        s = s.Substring(2);
                                    if (s.EndsWith("\n"))
                                        s = s.Substring(0, s.Length - 1);
                                    return s;
                                 })
                                .ToList();


In light of new information as a result of editing your question here is your answer:

//Write output while removing `\\` and `\n`
Console.WriteLine(
     string.Join(",", input.Split(',').ToList()
           .Select(serverName => serverName
               .Replace("\\", "")
               .Replace("\n", ""))
           .ToArray()));

You could use Regex.Replace() regular expressions instead of .Replace() to make matching more exact if you need more precise control.

Also, List is a kind of dynamic array, except it is strongly typed.

Further, in your example, you have a char array declared as delimiterChars but yet you don't use it anywhere. If it is not part of the example please don't include it, because it confuses people to what you are trying to achieve.


I'm not really sure what you are asking. But if my guess is correct, this may be what you need

string[] serverNames = new string[4];
serverNames[0] = "\\st1";
serverNames[1] = "\\st10";
serverNames[2] = "\\st4";
serverNames[3] = "\\st5";

do note that \n turns into a newline and \\ turns into a single \

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜