C語言string.h庫中的常用函數


strcat、strncat、strcmp、strncmp、strcpy、strncpy、strdup

》strcat

char strcat(char * str1,char * str2);
函數功能: 把字符串str2接到str1后面,str1最后的'\0'被取消
函數返回: str1
參數說明:
所屬文件: <string.h>

#include <stdio.h>
#include <string.h>
int main()
{
  char buffer[80];
  strcpy(buffer,"Hello ");
  strcat(buffer,"world");
  printf("%s\n",buffer);
  return 0;
}

》strncat

char strncat(char *dest, const char *src, size_t maxlen)
函數功能: 將字符串src中前maxlen個字符連接到dest中
函數返回:
參數說明:
所屬文件: <string.h>

#include <stdio.h>
#include <string.h>
char buffer[80];
int main()
{
  strcpy(buffer,"Hello ");
  strncat(buffer,"world",8);
  printf("%s\n",buffer);
  strncat(buffer,"*************",4);
  printf("%s\n",buffer);
  return 0;
}

》strcmp

int strcmp(char * str1,char * str2);
函數功能: 比較兩個字符串str1,str2.
函數返回: str1<str2,返回負數;str1=str2,返回 0;str1>str2,返回正數.
參數說明:
所屬文件: <string.h>

#include <string.h>
#include <stdio.h>
int main()
{
  char *buf1="aaa", *buf2="bbb",*buf3="ccc";
  int ptr;
  ptr=strcmp(buf2, buf1);
  if(ptr>0)
    printf("buffer 2 is greater thanbuffer 1\n");
  else
    printf("buffer 2 is less thanbuffer 1\n");
  ptr=strcmp(buf2, buf3);
  if(ptr>0)
    printf("buffer 2 is greater thanbuffer 3\n");
  else
    printf("buffer 2 is less thanbuffer 3\n");
  return 0;
}

》strncmp

int strncmp(char *str1,char *str2,int count)
函數功能: 對str1和str2中的前count個字符按字典順序比較
函數返回: 小於0:str1<str2,等於0:str1=str2,大於0:str1>str2
參數說明: str1,str2-待比較的字符串,count-比較的長度
所屬文件: <string.h>

#include<string.h>
#include<stdio.h>
int main()
{
   char str1[] ="aabbc";//
   char str2[] = "abbcd";//
   //為使測試程序更簡練,此處假定了strncmp只返回-1,0,1三個數
   char res_info[] = {'<','=','>'};
   int res;

   //前1個字符比較
   res = strncmp(str1, str2, 1);
   printf("1:str1%c str2\n", res_info[res+1]);

    //前3個字符比較
   res = strncmp(str1, str2, 3);
   printf("3:str1%c str2\n", res_info[res+1]);
}

》strcpy

char strcpy(char* str1,char* str2)
函數功能: 把str2指向的字符串拷貝到str1中去
函數返回: 返回str1,即指向str1的指針
參數說明:
所屬文件: <string.h>

#include <stdio.h>
#include <string.h>
int main()
{
        char string[10];
        char *str1="abcdefghi";
        strcpy(string,str1);
        printf("the string is:%s\n",string);
        return 0;
}

》strncpy

char *strncpy(char *dest, const char *src,intcount)
函數功能: 將字符串src中的count個字符拷貝到字符串dest中去
函數返回: 指向dest的指針
參數說明: dest-目的字符串,src-源字符串,count-拷貝的字符個數
所屬文件: <string.h>

#include<stdio.h>
#include<string.h>
int main()
{
   char*src = "bbbbbbbbbbbbbbbbbbbb";//20 'b's
   char dest[50] ="aaaaaaaaaaaaaaaaaaaa";//20 'a's
   puts(dest);
   strncpy(dest, src, 10);
   puts(dest);
   return0;
}

》strdup

char strdup(const char *s)
函數功能: 字符串拷貝,目的空間由該函數分配
函數返回: 指向拷貝后的字符串指針
參數說明: src-待拷貝的源字符串
所屬文件: <string.h>

#include <stdio.h>
#include <string.h>
#include <alloc.h>
int main()
{
	char *dup_str, *string="abcde";
	dup_str=strdup(string);
	printf("%s", dup_str);
	free(dup_str);
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM