1. 程式人生 > >字串操作函式解析

字串操作函式解析

        在程式設計的時候我們經常會用到一些庫函式來操作字串,例如strcmp,strlen,strcat,  strstr, strcpy,  strchar ,  memcpy,  memmov,  memset     接下來我們就看一看這些函式。

        1 strcmp:


          從msdn的解釋中可以看出字串比較這個函式有兩個引數string1和string2,而且這倆引數都是常量字串(const修飾)。返回值是一個int型。當string1小於string2的時候會返回一個小於0的數,當string1等於string2的時候會返回0,當string1小於string2的時候會返回一個大於0的數。我們可以根據返回值來判斷這兩個字串的關係。


例如 :  

#define _CRT_SECURE_NO_DEPRECATE 1
#include <stdio.h>    
#include <stdlib.h>   
#include <string.h>
int main()
{
	char str1[]="hello future";
	char str2[]="hello my future";
	int ret;
	ret = strcmp(str1,str2);
	if(ret>0)
		printf("str1大於str2");
	else if(ret=0)
		printf("str1等於str2");
	else
		printf("str1小於str2");
	system("pause");
    return 0;
}

    2 strlen:


      從msdn的解釋中可以看出這個函式有一個引數 const char *string,  返回值是一個size_t(無符號整形),因為字串的個數根本就不可能是一個負數。

我們來看看msdn給的例子:

Example

/*  STRLEN.C */

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

void main( void )
{
   char buffer[61] = "How long am I?";
   int  len;
   len = strlen( buffer );
   printf( "'%s' is %d characters long\n", buffer, len );
}


Output

'How long am I?' is 14 characters long


   3  strcat:



     strcat函式實現的功能是把一個字串連線到另一個字串的後面。既然是兩個字串連線就要有兩個引數即char *strDestination和const char *strSource; 返回值是一個char* 指標,指向strDestination的首元素地址,這樣有利於作為鏈式訪問使用。

#define _CRT_SECURE_NO_DEPRECATE 1
#include <stdio.h>    
#include <stdlib.h>   
#include <string.h>
int main()
{
	char str1[]="Do you want to ";
        char str2[]="play baketball?";
	printf("%s  \n",strcat(str1,str2));//返回值char * 作為首元素用於實現鏈式訪問
	system("pause");
        return 0;
}

      當我們使用strcat的時候有一點要注意,不能使用strcat(str1,str1)即給一個字串自身連線自己本身。否則會出現如下情況。


如果非要自身連線自身請使用strncat.

4 strstr:



這個函式的功能是在一個字串裡面尋找另一個字串是否存在。這個函式有兩個引數即const char *string ,const char *strcharset,返回值是一個char *指標。函式返回指向字串中第一次出現strcharset,或null如果strcharset不出現在字串。如果strcharset指向一個字串的長度為零,函式返回字串。

我們來看一個msdn中的例子 便於理解

Example

/* STRSTR.C */

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

char str[] =    "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] =   "         1         2         3         4         5";
char fmt2[] =   "12345678901234567890123456789012345678901234567890";

void main( void )
{
   char *pdest;
   int  result;
   printf( "String to be searched:\n\t%s\n", string );
   printf( "\t%s\n\t%s\n\n", fmt1, fmt2 );
   pdest = strstr( string, str );
   result = pdest - string + 1;
   if( pdest != NULL )
      printf( "%s found at position %d\n\n", str, result );
   else
      printf( "%s not found\n", str );
}


Output

String to be searched:
   The quick brown dog jumps over the lazy fox
            1         2         3         4         5
   12345678901234567890123456789012345678901234567890

lazy found at position 36


   5 strcpy:


這個函式實現的是字串拷貝功能。有兩個引數 char *strDestination 和 const char *strSource。從這倆引數我們就可以直接看出是把const char *strSource中的字串拷貝到char *strDestination中因為是改變char *strDestination中的內容所以要傳址。而使用const的修飾char *strSource使之成為常量字串是為了增加程式的健壯性(便於記憶倆引數的用處,放置倆引數放錯引起的不必要的錯誤)。而返回值char * 指向拷貝完成的字串首元素。便於鏈式訪問。

看看msdn的例子

Example

/* STRCPY.C: This program uses strcpy
 * and strcat to build a phrase.
 */

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

void main( void )
{
   char string[80];
   strcpy( string, "Hello world from " );
   strcat( string, "strcpy " );
   strcat( string, "and " );
   strcat( string, "strcat!" );
   printf( "String = %s\n", string );
}


Output

String = Hello world from strcpy and strcat!

  6 strchr:

        函式功能:在一個字串裡面尋找一個字元。這個函式有兩個引數 const修飾的常量字串char *string,和int型變數c。c是用來定位這個字元在常量字串string中的位置的。 char *指向的是要找的這個字元第一次出現在常量字串string中的位置(可能存在多個該字元)。如果不存在則表示不存在。

看看例子

Example

/* STRCHR.C: This program illustrates searching for a character
 * with strchr (search forward) or strrchr (search backward).
 */

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

int  ch = 'r';

char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] =   "         1         2         3         4         5";
char fmt2[] =   "12345678901234567890123456789012345678901234567890";

void main( void )
{
   char *pdest;
   int result;

   printf( "String to be searched: \n\t\t%s\n", string );
   printf( "\t\t%s\n\t\t%s\n\n", fmt1, fmt2 );
   printf( "Search char:\t%c\n", ch );

   /* Search forward. */
   pdest = strchr( string, ch );
   result = pdest - string + 1;
   if( pdest != NULL )
      printf( "Result:\tfirst %c found at position %d\n\n", 
              ch, result );
   else
      printf( "Result:\t%c not found\n" );

   /* Search backward. */
   pdest = strrchr( string, ch );
   result = pdest - string + 1;
   if( pdest != NULL )
      printf( "Result:\tlast %c found at position %d\n\n", ch, result );
   else
      printf( "Result:\t%c not found\n" );
}


Output

String to be searched: 
      The quick brown dog jumps over the lazy fox
               1         2         3         4         5
      12345678901234567890123456789012345678901234567890

Search char:   r
Result:   first r found at position 12

Result:   last r found at position 30


   7 memcpy:
功能:從快取中拷貝字元。 引數 void  *dest  (需要拷貝到的目的地) const void *src(拷貝源)

size_t  (需要拷貝的個數)  返回值  void *  (memcpy returns the value of dest.

例子:msdn給的這個例子  很長   但是實現的功能確實非常簡單的,看一眼就能明白。

Example

/* MEMCPY.C: Illustrate overlapping copy: memmove
 * handles it correctly; memcpy does not.
 */

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

char string1[60] = "The quick brown dog jumps over the lazy fox";
char string2[60] = "The quick brown fox jumps over the lazy dog";
/*                           1         2         3         4         5
 *                  12345678901234567890123456789012345678901234567890
 */

void main( void )
{
   printf( "Function:\tmemcpy without overlap\n" );
   printf( "Source:\t\t%s\n", string1 + 40 );
   printf( "Destination:\t%s\n", string1 + 16 );
   memcpy( string1 + 16, string1 + 40, 3 );
   printf( "Result:\t\t%s\n", string1 );
   printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );

   /* Restore string1 to original contents */
   memcpy( string1 + 16, string2 + 40, 3 );

   printf( "Function:\tmemmove with overlap\n" );
   printf( "Source:\t\t%s\n", string2 + 4 );
   printf( "Destination:\t%s\n", string2 + 10 );
   memmove( string2 + 10, string2 + 4, 40 );
   printf( "Result:\t\t%s\n", string2 );
   printf( "Length:\t\t%d characters\n\n", strlen( string2 ) );

   printf( "Function:\tmemcpy with overlap\n" );
   printf( "Source:\t\t%s\n", string1 + 4 );
   printf( "Destination:\t%s\n", string1 + 10 );
   memcpy( string1 + 10, string1 + 4, 40 );
   printf( "Result:\t\t%s\n", string1 );
   printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );
}


Output

Function:   memcpy without overlap
Source:      fox
Destination:   dog jumps over the lazy fox
Result:      The quick brown fox jumps over the lazy fox
Length:      43 characters

Function:   memmove with overlap
Source:      quick brown fox jumps over the lazy dog
Destination:   brown fox jumps over the lazy dog
Result:      The quick quick brown fox jumps over the lazy dog
Length:      49 characters

Function:   memcpy with overlap
Source:      quick brown dog jumps over the lazy fox
Destination:   brown dog jumps over the lazy fox
Result:      The quick quick brown dog jumps over the lazy fox
Length:      49 characters


    8  memmov:


函式功能:緩衝區資料移動。 引數 void  *dest  (需要移動到的目的地) const void *src(需要移動的資料來源)  size_t count (需要拷貝的型別位元組數)  返回值  void *  (memmove returns the value of dest.

例子:

Example

/* MEMCPY.C: Illustrate overlapping copy: memmove
 * handles it correctly; memcpy does not.
 */

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

char string1[60] = "The quick brown dog jumps over the lazy fox";
char string2[60] = "The quick brown fox jumps over the lazy dog";
/*                           1         2         3         4         5
 *                  12345678901234567890123456789012345678901234567890
 */

void main( void )
{
   printf( "Function:\tmemcpy without overlap\n" );
   printf( "Source:\t\t%s\n", string1 + 40 );
   printf( "Destination:\t%s\n", string1 + 16 );
   memcpy( string1 + 16, string1 + 40, 3 );
   printf( "Result:\t\t%s\n", string1 );
   printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );

   /* Restore string1 to original contents */
   memcpy( string1 + 16, string2 + 40, 3 );

   printf( "Function:\tmemmove with overlap\n" );
   printf( "Source:\t\t%s\n", string2 + 4 );
   printf( "Destination:\t%s\n", string2 + 10 );
   memmove( string2 + 10, string2 + 4, 40 );
   printf( "Result:\t\t%s\n", string2 );
   printf( "Length:\t\t%d characters\n\n", strlen( string2 ) );

   printf( "Function:\tmemcpy with overlap\n" );
   printf( "Source:\t\t%s\n", string1 + 4 );
   printf( "Destination:\t%s\n", string1 + 10 );
   memcpy( string1 + 10, string1 + 4, 40 );
   printf( "Result:\t\t%s\n", string1 );
   printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );
}

Output

Function:   memcpy without overlap
Source:      fox
Destination:   dog jumps over the lazy fox
Result:      The quick brown fox jumps over the lazy fox
Length:      43 characters

Function:   memmove with overlap
Source:      quick brown fox jumps over the lazy dog
Destination:   brown fox jumps over the lazy dog
Result:      The quick quick brown fox jumps over the lazy dog
Length:      49 characters

Function:   memcpy with overlap
Source:      quick brown dog jumps over the lazy fox
Destination:   brown dog jumps over the lazy fox
Result:      The quick quick brown dog jumps over the lazy fox
Length:      49 characters
 

    9   memset  :


功能:把指定的快取空間設定為指定的字元。    引數         void  *dest  (需要設定的目的地)                          c:需要設定的字元型別                 size_t count (需要設定的指定型別的個數)                   返回值  void *  (memmove returns the value of dest.

例子:比起之前幾個的繁瑣相當精簡

Example

/* MEMSET.C: This program uses memset to
 * set the first four bytes of buffer to "*".
 */

#include <memory.h>
#include <stdio.h>

void main( void )
{
   char buffer[] = "This is a test of the memset function";

   printf( "Before: %s\n", buffer );
   memset( buffer, '*', 4 );
   printf( "After:  %s\n", buffer );
}

Output

Before: This is a test of the memset function
After:  **** is a test of the memset function
在使用這些字串操作函式的時候我們需要注意的地方是 :

    1 各個引數的意義,我們可以通過const修飾減少一些不必要的錯誤引起的失。

    2  巧妙的利用返回值,使程式更加的巧妙。