Comparing two equal strings doesnt work

I have a list of strings (containing hockey player names) and I want to find the index for a specific name.I never had such an easy problem before and it is driving my insane.
I tried this:
player and index are both "Connor McDavid"
player = Player(1);
index1 = string(200);
logic = strcmp(index1 ,player);
Here are screenshots too ensure that they contain the same value.
Unbenannt.PNG
Unbenannt.PNG
logic should return a 1 but it returns 0. I tried == too but it doesnt help.
Pls help me, i dont know what to do anymore.

9 个评论

string(200) is "200" since R2016b unless you have a variable named "string" in scope. If you do then is it a string object or a cell array of character vectors, or a character vector?
the badly named variable string contains 886 string entries, so I think it is a character vector. I tried renaming already, it yields the same result.
Unbenannt.PNG
I figured out that it has to do something with the spaces in between the names.
i tried this:
chr = convertStringsToChars(index1)
chr1 = convertStringsToChars(player)
chr == chr1
and i get this result:
ans =
1×14 logical array
1 1 1 1 1 1 0 1 1 1 1 1 1 1
so i tried to erase both spaces with something like this:
index1= strrep(index1,' ','')
but the result is still this:
index1 =
"Connor McDavid"
Convert both strings to numbers and tell us what the result it. I'm thinking the space is different. Type this
player + 'A'
index1 + 'A'
Edit: you seem to have solved it while I was writing this. But my hunch was right!
this is the answer:
ans =
"Connor McDavid0"
ans =
"Connor McDavid0"
player{1}+0
index1{1}+0
You need to extract the characters from the string object to look at the character codes
ans =
67 111 110 110 111 114 32 77 99 68 97 118 105 100
ans =
67 111 110 110 111 114 160 77 99 68 97 118 105 100
your prediction is indeed correct, the space is different.
What is the most efficient way to erase this problem ?
thank you both for your help!
Haha, oh yeah, they are strings.
char(player)-'A'
160 is U+00A0, "non-breaking space"
player = replace(player, char(160), ' ');
index1 = replace(index1, char(160), ' ');
but it would probably make more sense to replace all of the 160 in your data source (perhaps immediately after retrieving it) instead of doing the replacement each iteration.

回答(1 个)

This can be solved by using the "ismember" function, refer the below example:
A = ["John"; "Lee" ; "James"; "Lee"];
B = "Lee";
index = ismember(A,B)
The output is
index =
4×1 logical array
0
1
0
1

此问题已关闭。

关闭:

2021-8-20

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by