strcpy、sprintf和memcpy的區別
下面代碼說明:
#include <iostream>
using namespace std;
#include <string.h>
void strcpyMethod()
{
/*
char *strcpy(char *dest, const char *src) :C 庫函數 把 src 所指向的字符串複製到 dest
*/
char str1[15] = "AAAAAAAAA";
char str2[8] = "abcdefg"; //由於字符串,還要加個'\0'的結束符,所以是8
char str3[] = "12345678890";
cout << "str2:" << str2 << endl;
strcpy(str1, str2); //將str2 拷貝給str1
//strcpy(str1, str3); //error: 越界:str3長度大於str1數組大小
cout << "str1:" << str1 << endl;
//注意:字符串都以'\0'結束
cout << str2[0] << endl;
cout << str2[1] << endl;
cout << str2[2] << endl;
cout << str2[3] << endl;
cout << str2[4] << endl;
cout << str2[5] << endl;
cout << str2[6] << endl;
cout << str2[7];
cout << "體現出結束標誌符" << endl;
cout << str1[0] << endl;
cout << str1[1] << endl;
cout << str1[2] << endl;
cout << str1[3] << endl;
cout << str1[4] << endl;
cout << str1[5] << endl;
cout << str1[6] << endl;
//cout << str1[7];
cout << "Test" << endl;
//strcpy(str1, "hello world"); //error: 越界:hello world長度大於str1數組大小
strcpy(str1, "hello");
cout << str1 << endl;
/*
輸出:
str2:abcdefg
str1:abcdefg
a
b
c
d
e
f
g
體現出結束標誌符
a
b
c
d
e
f
g
Test
hello
*/
}
void sprintfMethod()
{
/*
int sprintf(char *str, const char *format, ...) : 發送格式化輸出到 str 所指向的字符串
*/
char str_spr[100];
sprintf(str_spr, "I am a %s hi %d C++ %c", "student", 123, 'a'); //格式化字符串,%s :字符串 %d:整數 %c:字符
cout << str_spr << endl;
cout << "-----------------------------" << endl;
char str_temp[] = "h%c 1%d1 %s C++!";
char buf[100];
sprintf(buf, str_temp, 'i', 2, "hello"); //str_temp 爲待格式化的字符串,str_temp格式化輸出到buf
cout << "buf: " << buf << "\tlen: " << " " << strlen(buf) << endl;
/*
輸出:
I am a student hi 123 C++ a
-----------------------------
buf: hi 121 hello C++! len: 17
*/
}
void memcpyMethod()
{
/*
void *memcpy(void *str1, const void *str2, size_t n) :C 庫函數 從存儲區 str2 複製 n 個字符到存儲區 str1
*/
char str1[] = "abcdefg";
char str2[10];
char str3[10];
memcpy(str2, str1, strlen(str1)+1); //由於由於strlen只是獲得str1的實際長度,並沒包含'\0',所以加1將'\0'包含進去
memcpy(str3, str1, 2);
str3[2] = '\0'; //由於沒有'\0',所以要手動添加結束標誌符
cout << str2 << endl;
cout << str3 << endl;
/*
輸出:
abcdefg
ab
*/
//覆蓋原數據
char dest [] = "123456";
const char *src = "*****";
memcpy(dest, src, strlen(src));
//注意:從src中複製到dest的字符串的長度不能超過dest的實際長度,否則會因爲越界報錯
//若要不報錯,則要事先設計 dest的大小 大於 strlen(src)
cout << dest << endl;
//輸出: *****6
const char *p = "ABCDEFGH";
char pstr[20];
memcpy(pstr, p + 2, 5); //從p的第二個位置開始連續複製5個到pstr中
pstr[5] = '\0';
cout << "p: "<<p << endl;
cout << "pstr:"<<pstr << endl;
/*
輸出:
p: ABCDEFGH
pstr:CDEFG
*/
}
int main()
{
strcpyMethod();
sprintfMethod();
memcpyMethod();
return 0;
}
/*
strcpy、sprintf和memcpy三者的區別:
(1)操作對象不同,strcpy的兩個操作對象均爲字符串類型;
sprintf的源操作對象可以是多種類型,目的操作對象是字符串;
memcpy的兩個操作對象是兩個可任意操作的內存地址,不限於任何數據類型
(2)執行效率不同,memcpy最高,strcpy次之,sprintf最低
(3)實現功能不同,strcpy實現兩個字符串變量之間的拷貝,
sprintf實現其他數據類型格式化到字符串之間的轉化,
memcpy 主要是內存塊之間的拷貝
*/
//三者都有拷貝的功能,針對對象不同,應結合實際情況選擇使用