Reputation: 13
I'm currently trying to do string comparisons - I know it's not best to do so, but I need to for this solution.
If I were parsing a line such as: Raiden: HelloWorld
, I would want to extract the separate strings Raiden
and HelloWorld
for further use.
I currently do achieve this by performing the following:
var list = channelMessage.Split(' ', ':', '\n', '\0');
However, when printing the result and length of each item in list
the HelloWorld
string's length is incorrect.
Output:
Raiden | length: 6
HelloWorld | length: 11
HelloWorld
's length should be 10, not 11. I'm assuming there's null characters somewhere in the line, but cannot figure out how to remove them all.
Sidenote: If I remember correctly, c#'s strings are arrays, and the last character of the array is a '\0' but I tried removing it (as seen above)
Is my assumption correct, and how can I correctly get HelloWorld
's length to 10?
Upvotes: 1
Views: 179
Reputation: 249
Split
will likely give you trouble in this solution since it doesn't handle a huge range of input.
Something like a regex might be better because of the char ranges, something like \W+
would match any non-world sequence.
example:
Regex.Split("asdadaSD asdsad asdsad \n asdasdsd", "\\W+")
Upvotes: 0
Reputation: 1116
you're supposed to use Trim()
to remove whitespaces around a string
See : https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=netframework-4.8
This would result in
var list = channelMessage.Split(':').Select(s => s.Trim());
I'm also using the Select()
from linq. This code would be similar to:
var list = channelMessage.Split(':');
var list2 = new List<string>();
foreach(string s in list)
list2.add(s.trim());
Upvotes: 2
Reputation: 13965
The problem is that when you split Raiden: HelloWorld
on : you end up with this:
Raiden
_HelloWorld
Where the _ represents an empty whitespace.
Here's one possible solution. When I run this console app:
static void Main(string[] args)
{
var test = "Raiden: HelloWorld";
List<string> split = test.Split(':').Select(t => t.Trim()).ToList();
Console.WriteLine(split[0].Length);
Console.WriteLine(split[1].Length);
Console.ReadLine();
}
I get:
6
10
Upvotes: 0