C語言--字符處理函數

C語言提供了豐富的字符串處理函數, 大體可分爲字符串的輸入、輸出、合併、修改、比較、轉換、複製、搜索幾類。 使用這些函數可大大減輕編程的負擔。用於輸入輸出的字符串函數,在使用前應包含頭文件"stdio.h",使用其它字符串函數則應包含頭文件"string.h"。編程

下面介紹幾個最經常使用的字符串函數。數組

1. 字符串輸出函數 puts函數

   格式:  puts (字符數組名)spa

   功能:把字符數組中的字符串輸出到顯示器。 即在屏幕上顯示該字符串。字符串

【例】get

#include"stdio.h"input

main()字符串處理

{string

  char c[]="BASIC\ndBASE";io

  puts(c);

}


2. 字符串輸入函數gets

   格式:  gets  (字符數組名)

   功能:從標準輸入設備鍵盤上輸入一個字符串。

 本函數獲得一個函數值,即爲該字符數組的首地址。

【例】

#include"stdio.h"

main()

{

  char st[15];

  printf("input string:\n");

  gets(st);

  puts(st);

}

【注】

能夠看出當輸入的字符串中含有空格時,輸出仍爲所有字符串。說明gets函數並不以空格做爲字符串輸入結束的標誌,而只以回車做爲輸入結束。這是與scanf函數不一樣的。


3. 字符串鏈接函數strcat

   格式:  strcat (字符數組名1,字符數組名2)

   功能:把字符數組2中的字符串鏈接到字符數組1 中字符串的後面,並刪去字符串1後的串標誌\0。本函數返回值是字符數組1的首地址。

【例】

#include"string.h"

main()

{

  static char st1[30]="My name is ";

  int st2[10];

  printf("input your name:\n");

  gets(st2);

  strcat(st1,st2);

  puts(st1);

}

【注】

本程序把初始化賦值的字符數組與動態賦值的字符串鏈接起來。要注意的是,字符數組1應定義足夠的長度,不然不能所有裝入被鏈接的字符串。


4. 字符串拷貝函數strcpy

格式:  strcpy (字符數組名1,字符數組名2)

   功能:把字符數組2中的字符串拷貝到字符數組1中。串結束標誌\0也一同拷貝。字符數名2,也能夠是一個字符串常量。這時至關於把一個字符串賦予一個字符數組。

【例】

#include"string.h"

main()

{

  char st1[15],st2[]="C Language";

  strcpy(st1,st2);

  puts(st1);printf("\n");

}


5. 字符串比較函數strcmp

 格式:  strcmp(字符數組名1,字符數組名2)

   功能:按照ASCII碼順序比較兩個數組中的字符串,並由函數返回值返回比較結果。

          字符串1=字符串2,返回值=0;

          字符串2〉字符串1,返回值〉0;

          字符串1〈字符串2,返回值〈0。

本函數也可用於比較兩個字符串常量,或比較數組和字符串常量。

【例】

#include"string.h"

main()

{ int k;

  static char st1[15],st2[]="C Language";

  printf("input a string:\n");

  gets(st1);

  k=strcmp(st1,st2);

  if(k==0) printf("st1=st2\n");

  if(k>0) printf("st1>st2\n");

  if(k<0) printf("st1<st2\n");

}


6. 測字符串長度函數strlen

   格式:  strlen(字符數組名)

   功能:測字符串的實際長度(不含字符串結束標誌\0) 並做爲函數返回值。

【例】

#include"string.h"

main()

{ int k;

  static char st[]="C language";

  k=strlen(st);

  printf("The lenth of the string is %d\n",k);

}

相關文章
相關標籤/搜索