Reputation: 1
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();
Upvotes: 0
Views: 2167
Reputation: 12674
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.
Upvotes: 1
Reputation: 86738
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();
Upvotes: 2
Reputation: 6901
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 \
Upvotes: 0