c++字符數組函數總結


參考於https://blog.csdn.net/Hachi_Lin/article/details/79772451

1.strcat()
格式:

  strcat(字符數組1,字符數組2)
作用:
  字符串連接函數,其功能是將字符數組2中的字符串連接到字符數組1中字符串的后面,並刪去字符串1后的串結束標志”\0”。需要注意的是字符數組的長度要足夠大,否則不能裝下連接后的字符串。
例子:

 1 #include <bits/stdc++.h>  2 using namespace std;  3 int main() {  4 char str1[30], str2[20];  5 cout << "please input string1:" << endl;  6 cin >> str1;  7 cout << "please input string2:" << endl;  8 cin >> str2;  9  strcat(str1, str2); 10 cout << "Now the string is:" << endl; 11 cout << str1 << endl; 12 return 0; 13 }

運行結果:

2.strcpy()
格式:
    strcpy(字符數組1,字符數組2)
說明:
  字符串復制函數,其功能是把數組2中的字符串復制到字符數組1中。字符串結束標志”\0”也一同復制。要求字符數組1應有足夠的長度,否則不能全部裝入所復制的字符串。另外,字符數組1必須寫成數組名形式,而字符數組2可以是字符數組名,也可以是一個字符串常量。
例子:

 1 #include <bits/stdc++.h>  2 using namespace std;  3 int main() {  4 char str1[30], str2[20];  5 cin >> str1; //給str1賦值   6 cout << "str1為:" << str1 << endl;  7 strcpy(str2, "456789"); //給str2賦值   8 cout << "str2為:" << str2 << endl;  9  strcpy(str1, str2); 10 cout << "str1為:" << str1 << endl; 11 return 0; 12 }

運行結果:

 3.strcmp()
格式:
    strcmp(字符數組1,字符數組2)
說明:
  字符串比較函數,其功能是按照ASCII碼順序比較兩個數組中的字符串,並有函數返回比較結果。如果字符串1=字符串2,返回0;如果字符串1>字符串2,返回正數;如果字符串1<字符串2,返回值負數。
例子:

 1 #include <bits/stdc++.h>  2 using namespace std;  3 int main() {  4 char str1[30], str2[30];  5 cin >> str1;  6 cout << "str1為:" << str1 << endl;  7 cin >> str2;  8 cout << "str2為:" << str2 << endl;  9 cout << strcmp(str1, str2) << endl; 10 return 0; 11 }

運行結果:

 

4.strncmp()

格式:
    strncmp(字符數組1,字符數組2,長度n)
說明:
  同strcmp()函數,加入了要比較的最大字符數n。
例子:

 1 #include <bits/stdc++.h>  2 using namespace std;  3 int main() {  4 char str1[30], str2[30];  5 cin >> str1;  6 cout << "str1為:" << str1 << endl;  7 cin >> str2;  8 cout << "str2為:" << str2 << endl;  9 int n; 10 cin >> n; 11 cout << "n為:" << n << endl; 12 cout << strncmp(str1, str2, n) << endl; 13 return 0; 14 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM