Comparing strings (C)

In C, you can compare single characters (chars) by using the comparion operator ==, however, this method is not valid for comparing arrays of chars, or strings. Instead, you must use a function that compares each of the chars within the arrays in turn. This may sound complex to the beginner, but fortunately there is a standard C function that does this for you.


#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);


The first, strcmp(), does exactly as described above, the second, strncmp(), checks only the first n characters of the array for equality.


Here is an example of how not to do things.


#include <stdio.h>  
#include <string.h>  


int main(void)
{
  char *foo = "hello";
  char *bar = "hello";
  if (foo == bar)  /* Wrong ! */
    puts("Strings equal");
  else
    puts("Strings do not equal");
  
  return 0;
}






Here are some examples of these functions in use.


#include <stdio.h> 
#include <string.h> 


int main(void)
{
  char *foo = "hello";
  char *bar = "world";
  if (strcmp(foo, bar) == 0) 
    puts("Strings equal");
  else 
    puts("Strings do not equal");
  
  return 0;
}


/* 
 * Output
 Strings do not equal
 *
 */
 




This next example shows the consideration needed when reading a string from the user. It deals with removing the newline character from the input array. This issue is also covered here.


#include <stdio.h> 
#include <string.h> 


int main(void)
{
  char Owner[] = "Hammer";
  char buf[BUFSIZ];
  
  printf ("You are at the house door.\nEnter your name:");
  fflush(stdout);
  if (fgets(buf, sizeof(buf), stdin))
  {
    char *p = strchr(buf, '\n');
    if (p) *p = '\0';
    if (strcmp(Owner, buf) == 0)
      printf ("Welcome home %s\n", Owner);
    else
      printf ("Agghh, who let %s in here?!\n", buf);
  }
  
  return 0;
}


/*
 * Output:
 You are at the house door.
 Enter your name:Hammer
 Welcome home Hammer
 
 ---
 
 You are at the house door.
 Enter your name:Trouble
 Agghh, who let Trouble in here?!
 *
 */




This next example shows how to use strncpy() to compare the first few characters of the arrays, rather than all of them.


#include <stdio.h>  
#include <string.h>  


int main(void)
{
  char *foo = "hello";
  char *bar = "help me";
  if (strncmp(foo, bar, 3) == 0)
    puts("First 3 chars are equal");
  else
    puts("First 3 chars are NOT equal");
  
  return 0;
}


/*
 * Output
 First 3 chars are equal
 *
 */



From: www.Cprogramming.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值