2012年1月7日 星期六

string.h - memchr,memset,memcmp,memapy,memmove

 memchr

Declaration:
vo

id *memchr(const void *str, int c, size_t n);
  搜尋mem記憶體內容的前n個字元是否有ch字元,回傳值為該ch字元的位址,若無則回傳0


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

int main()
{
  char s[]="I LOVE C and C++.";
  printf("%s\n",(memchr(s,'L',18)));
  printf("%s\n",(strchr(s,'L')));
 
  char bs[]="1111 1010 0101 1100 0011";
  printf("%s\n",(memchr(bs,'11',40)));
  printf("%s\n",(strchr(bs,'11')));


  char nulls[]="'\0' 1111 1010 0101 1100 0011";
  printf("%s\n",(memchr(nulls,'11',40)));
  printf("%s\n",(strchr(nulls,'11')));
 
 
  system("pause");
}

    RESULT:
    LOVE C and C++.
    LOVE C and C++.
    1111 1010 0101 1100 0011
    1111 1010 0101 1100 0011

   1111 1010 0101 1100 0011
   (null)  <=如果字串裡有null('\0') ,strchr一遇到 NULL就會停止 */


 
  memchr與strchr 不同的地方是
  strchr stops when it hits a null character but memchr does not;
  this is why the former does not need a length parameter but the latter does.

 




 memcmp

Declaration:
int memcmp(const void *str1, const void *str2, size_t n);

  記憶體比對,比對mem1和mem2所指的記憶體空間的前n個字元,回傳值為相異的字元差



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

int main()
{
  char s[]="LOVE C and C++";
  char t[]="LOVE Is A Clothes";
  printf("%d\n",(memcmp(s,t,4)));
  printf("%d\n",(memcmp(s,t,7)));
  printf("%d\n",(memcmp(t,s,7)));
 
  /*RESULT:
    0
    -1
    1   */
 
 
  system("pause");
}


memcpy

Declaration:
void* memcpy(void* destn,const void* source,size_t n)
    記憶體拷貝,從soutce中拷貝n個字元至destn,回傳值為destn位址
 

memccpy

void* memccpy(void* destn,const void* source,int ch,size_t n)
  記憶體拷貝,拷貝從ch出現以後的n各字元,從soutce中拷貝n個字元至destn,,並回傳出現ch字元的下一個字元的位址 若未出現ch字元則回傳0


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

int main()
{
  char s[]="123456789 I LOVE C and C++";
  char t[35];
  printf("memcpy result :%s\n",(memcpy(t,s,30))); 
  printf("memccpy result:%s\n",(memccpy(t,s,'I',30))); 
 
  /*RESULT:
    memcpy result :123456789 I LOVE C and C++
    memccpy result: LOVE C and C++
   
  */
 
  system("pause");




memmove

Declaration:
void *memmove(void *str1, const void *str2, size_t n);
Copies n characters from str2 to str1. If str1 and str2 overlap the information is first completely read from str1 and then written to str2 so that the characters are copied correctly. Returns the argument str1.
記憶體拷貝,從soutce中拷貝n個字元至destn,但destn和source的區域若有重疊,也能進行拷貝
 但執行效率比memcpy()略慢些

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

int main()
{
    char s[40] = ".............out of work";
    char t[20] = "future Job";
   
    memmove(s, t, 10);
   
    printf("%s\n", s);
    

 
  /*RESULT:
   future Job...out of work */
 
  system("pause");
}


memset

Declaration:
void *memset(void *str, int c, size_t n);
Copies the character c (an unsigned char) to the first n characters of the string pointed to by the argument str. The argument str is returned.

可以參考  memset那篇

沒有留言:

張貼留言