一、memchr函數,字元定位。 Locate character in block of memory
//1、memchr函數,字元定位。 Locate character in block of memory
// void * memchr ( const void *, int, size_t );
char * pch;
char str[] = "Example string";
pch =(char *) memchr(str,'p',strlen(str)); //返回的指標
if(pch != NULL){ //找不到,返回NULL
cout<<pch<<endl; // 《《輸出: ple string
cout<<"'p'在位置:"<<pch-str+1; //《《輸出: 'p'在位置:5
//指標在加減運算後,輸出為數字 (下標)
}
二、memcmp函數 比較兩個字串占記憶體的大小。
int memcmp ( const void * ptr1, const void * ptr2, size_t num ); num為比較的位元組數
char str1[256];
char str2[256];
int n;
gets(str1); //gao
gets(str2);//tong
n = memcmp(str1, str2, 256); //256為比較的位元組數,一個字元佔一byte
cout<<n<<endl; //輸出:-1
return 0;
三、memcpy函數, 複製指定的位元組數,返回複製的目的 地址
void * memcpy ( void * destination, const void * source, size_t num );
char str1[]="Sample string";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1); //strlen(str1)+1,因為字串後面有'\0'
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
// 輸出:
// str1: Sample string
// str2: Sample string
// str3: copy successful
四、memmove函數 Move block of memory
//memmove函數 Move block of memory
char str[] = "gao love tong";
char * p;
p = (char *)memmove(str+9, str+4,4); //
cout<<str<<endl<<p;
//輸出:
// gao love love
// love
五、memset函數 Fill block of memory
void * memset ( void * ptr, int value, size_t num );
char str[] = "almost every programmer should know memset!";
memset(str,'-',6); //'-'直接轉換為數字儲存,6是位元組數
cout<<str; //輸出:------ every programmer should know memset!
六、strcat 函數 ,串連兩個字串
char * strcat ( char * destination, const char * source );
七、strchr,尋找字元。Locate first occurrence of character in string
const char * strchr ( const char * str, int character ); char * strchr ( char * str, int character );
char str[] = "this is a sample string";
char * pch;
pch = strchr(str, 's');
while(pch != NULL){
cout<<"found at:"<<pch-str+1<<enl; //輸出找到的字元下標
pch = strchr(pch+1,'s'); //
}
found at:4
found at:7
found at:11
found at:18
八、strcmp函數,字串比較
int strcmp ( const char * str1, const char * str2 );
char * c1;
char * c2;
c1 = "abd";
c2 = "abcde";
cout<<strcmp(c1,c2);
輸出:1
九、strcoll函數 功能和strcmp類似
十、strcpy函數 字串複製
十一、strstr 函數,尋找子串
十二、strpbrk 匹配字串2中的所有字元
char * strpbrk ( char * str1, const char * str2 );
char str[] = "This is a sample string";
char key[] = "aeiou";
char * pch;
printf ("Vowels in '%s': ",str);
pch = strpbrk (str, key);
while (pch != NULL)
{
printf ("%c " , *pch);
pch = strpbrk (pch+1,key);
}
printf ("\n");
output:
Vowels in 'This is a sample string': i i a a e i
十三、strrchr 尋找最後出現的字元。 和 strchr相反