Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

strncmp

HI

I am experiencing problem with following statement
int comp = strncmp((array+middle),target,strlen(target));

I am trying to compare the target (player name) with the player name at array+middle position
However, by using strncmp, I do not get expected result because of 'strlen(target)'

For instance,

array+middle  --> super_player
target --> su

this two are not same but in fact the statement return 0 since I am only comparing su with super_player

I am wondering how can I compare su with the entire "super_player" instead of su

This statement is for comparison in my  binary search statement.
0
icysmarty
Asked:
icysmarty
  • 2
  • 2
1 Solution
 
peterchen092700Commented:
you don't need strncmp for that.


array+middle is a perfectly valid string (e.g. if array == "the super_player", array+4=="super_player")
so in fact you can use

strcmp(array+middle, target)
0
 
icysmartyAuthor Commented:
strcmp does not work for my case cause the array has fixed-length record of playername

like
array ={superman--ultraman--hero------andsoon---}
- stands for space
0
 
peterchen092700Commented:
for most scenarios, it would be best to split up the arreay (e.g. using strtok). If this is not an option, or the comparison the only problem, you can do the following:


{
   int targetLen = strlen(target);
   char * spacePosPtr = strchr(array+middle);  // find space position
   // calculate comparison length
   int cmpLen = spacePosPtr ? spacePosPtr-(array+middle) : strlen(array+middle);
   // compare only if lengths are the same
   bool equal  (cmpLen == targetLen) ? strncmp(array+middle,target,targetLen)==0 : false;
}    

HTH
Peter
0
 
icysmartyAuthor Commented:
Yeah, you are right.
I should do that.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now