user3591111
user3591111

Reputation: 102

String from label.text weird behaviour

So I have a Label being initialized by a WebService. I want to see if that label contains any commas. The problem is, even if the label has commas, Contains() returns false and if I do a Split(), the array is only 1 element long, containing the entire string.

// text is "255,255,0,0"
string wat = myLabel.Text;
string[] wats = wat.Split(',');

// This IF never happens, for some reason
if (wat.Contains(","))
{
    anotherLabel.Text = wats[0] + " VS " + wats[1];
}

Why don't Split() and Contains() work? Can it be some kind of diferent encode in the string that comes from the label? If I do wat = wat + ",", then Contains()returns True.

Upvotes: 1

Views: 86

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Unicode symbols are often weird. Unicode has a lot of commas, e.g.

string wat = "255,255,0,0"; // Full range commas

bool hasComma = wat.Contains(','); // false

If wat.Contains(',') returns false then delimiters are not commas ,. You can check it with string decoded:

string wat = myLabel.Text;

// Let's have a close look at wat: which characters (codes included) does it contain
MessageBox.Show(
  $"wat: [{wat}] encoded as {string.Join(" ", wat.Select(c => ((int)c).ToString("x4")))}");

You should get

wat: [255,255,0,0] encoded as 0032 0035 0035 002c 0032 0035 0035 002c 0030 002c 0030

if not check what character code(s) do you have instead of expected 002c.

Upvotes: 3

Jacob
Jacob

Reputation: 738

The following line is always going to evaluate to false:

if (wats.Contains(","))

string.Split(',') will only return the values in between commas as you are specifying a comma as your delimiter. None of the items in the array will ever contain a comma.

If you want to check whether your label text contains commas simply do:

if (lblteste.Text.Contains(','))

Upvotes: -1

Related Questions