c++(字串處理函數)

來源:互聯網
上載者:User

 

#include <iostream.h>
#include <string.h>
void main(void)
{
 char str1[10] = {"Tsinghua "};
 char str2[10] = {"Computer"};
 cout<<strncpy(str1,str2,3)<<endl;
}

運行結果:Comnghua

注意:字串source中前numchars個字元將覆蓋掉字串destination中前numchars個字元!

strcat(char target[], const char source[]);

strcat:將字串source接到字串target的後面。
strcat函數應用舉例
原型:strcat(char target[], const char source[]);
功能:將字串source接到字串target的後面
常式:

#include <iostream.h>
#include <string.h>
void main(void)
{
 char str1[] = {"Tsinghua "};
 char str2[] = {"Computer"};
 cout<<strcpy(str1,str2)<<endl;
}

運行結果:Tsinghua Computer

注意:在定義字元數組1的長度時應該考慮字元數組2的長度,因為串連後新字串的長度為兩個字串長度之和。進行字串串連後,字串1的結尾符將自動被去掉,在結尾串末尾保留新字串後面一個結尾符。

strncat(char target[], const char source[], int numchars);

strncat:將字串source的前numchars個字元接到字串target的後面。
strncat函數應用舉例:
原型:strncat(char target[], const char source[], int numchars);
功能:將字串source的前numchars個字元接到字串target的後面
常式:

#include <iostream.h>
#include <string.h>
void main(void)
{
 char str1[] = {"Tsinghua "};
 char str2[] = {"Computer"};
 cout<<strncat(str1,str2,3)<<endl;
}

運行結果:Tsinghua Com

int strcmp(const char firststring[], const char secondstring);

strcmp:比較兩個字串firststring和secondstring。
strcmp函數應用舉例
原型:int strcmp(const char firststring[], const char secondstring);
功能:比較兩個字串firststring和secondstring
常式:

#include <iostream.h>
#include <string.h>
void main(void)
{
 char buf1[] = "aaa";
 char buf2[] = "bbb";
 char buf3[] = "ccc";
 int ptr;
 ptr = strcmp(buf2,buf1);
 if(ptr > 0)
  cout<<"Buffer 2 is greater than buffer 1"<<endl;
 else
  cout<<"Buffer 2 is less than buffer 1"<<endl;
 ptr = strcmp(buf2,buf3);
 if(ptr > 0)
  cout<<"Buffer 2 is greater than buffer 3"<<endl;
 else
  cout<<"Buffer 2 is less than buffer 3"<<endl;
}

運行結果是:Buffer 2 is less than buffer 1
                 Buffer 2 is greater than buffer 3

strlen( const char string[] );

strlen:統計字串string中字元的個數。  
strlen函數應用舉例
原型:strlen( const char string[] );
功能:統計字串string中字元的個數
常式:

#include <iostream.h>
#include <string.h>
void main(void)
{
  char str[100];
  cout<<"請輸入一個字串:";
  cin>>str;
  cout<<"The length of the string is :"<<strlen(str)<<"個"<<endl;
}

運行結果The length of the string is x (x為你輸入的字元總數字)

注意:strlen函數的功能是計算字串的實際長度,不包括'/0'在內。另外,strlen函數也可以直接測試字串常量的長度,如:strlen("Welcome")。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.