C 標準庫

1.atoi()

int atoi(const char *str)

int atoi(const char *str) 把參數 str 所指向的字符串轉換爲一個整數(類型爲 int 型)。

  • 參數
    str – 要轉換爲整數的字符串。
  • 返回值
    該函數返回轉換後的長整數,如果沒有執行有效的轉換,則返回零。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atoi(str);
   printf("字符串值 = %s, 整型值 = %d\n", str, val);

   strcpy(str, "runoob.com");
   val = atoi(str);
   printf("字符串值 = %s, 整型值 = %d\n", str, val);

   return(0);
}
字符串值 = 98993489, 整型值 = 98993489
字符串值 = runoob.com, 整型值 = 0

2.strcmp()

int strcmp(const char *str1, const char *str2)

int strcmp(const char *str1, const char *str2) 把 str1 所指向的字符串和 str2 所指向的字符串進行比較。

  • 參數
    str1 – 要進行比較的第一個字符串。
    str2 – 要進行比較的第二個字符串。
  • 返回值
    該函數返回值如下:
    如果返回值 < 0,則表示 str1 小於 str2。
    如果返回值 > 0,則表示 str2 小於 str1。
    如果返回值 = 0,則表示 str1 等於 str2。
#include <stdio.h>
#include <string.h>

int main ()
{
   char str1[15];
   char str2[15];
   int ret;


   strcpy(str1, "abcdef");
   strcpy(str2, "ABCDEF");

   ret = strcmp(str1, str2);

   if(ret < 0)
   {
      printf("str1 小於 str2");
   }
   else if(ret > 0) 
   {
      printf("str2 小於 str1");
   }
   else 
   {
      printf("str1 等於 str2");
   }
   
   return(0);
}
str2 小於 str1

3.sprintf()

int sprintf( char *buffer, const char *format, [ argument] … );

把第三部分的數據,按照第二部分格式化字符的格式,把第三部分的數據進行”格式化“,然後在把格式化後的數據類型,存儲到字符串的緩存區間裏去。

  • 參數
    buffer – char型指針,指向將要寫入的字符串的緩衝區。
    format – 格式化字符串。即可選參數的想要輸入的數據類型。
    [argument]… – 可選參數,可以是任何類型的數據。

  • 整數轉化爲字符串:

#include "stdio.h"

int main(void)
{
	char str[12];

	sprintf(str,"%d",111);
	printf("str = %s\n",str);
	while(1);
}
str = 111

4.strtok

char *strtok(char *str, const char *delim)

char *strtok(char *str, const char *delim) 分解字符串 str 爲一組字符串,delim 爲分隔符。

  • 參數
    str – 要被分解成一組小字符串的字符串。
    delim – 包含分隔符的 C 字符串。
  • 返回值
    該函數返回被分解的第一個子字符串,如果沒有可檢索的字符串,則返回一個空指針。
#include <string.h>
#include <stdio.h>
 
int main () {
   char str[80] = "This is - www.csdn.com - website";
   const char s[2] = "-";
   char *token;
   
   /* 獲取第一個子字符串 */
   token = strtok(str, s);
   
   /* 繼續獲取其他的子字符串 */
   while( token != NULL ) {
      printf( "%s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}
This is 
 www.csdn.com 
 website

5.toupper

6.strcpy

7.memset

8.strlen

size_t strlen(const char *str)

size_t strlen(const char *str) 計算字符串 str 的長度,直到空結束字符,但不包括空結束字符。

  • 參數
    str – 要計算長度的字符串。
  • 返回值
    該函數返回字符串的長度。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章