顯示具有 字串 標籤的文章。 顯示所有文章
顯示具有 字串 標籤的文章。 顯示所有文章

2009年9月21日 星期一

C/C++筆記-用static_cast轉換C,C++字串

//C++字串轉C字串
char c_stype[100];
string a_string("something");
strcpy(c_style,a_string.c_str());

//C字串轉C++字串
a_string = c_style;
a_string = static_cast(c_style); //使用static_cast

/* C字串稍快一點,但使用strcpy和strcat有超過字串範圍的風險 */
##ShowAll##

C/C++筆記-strcpy和strcat超出字串範圍的風險

strcpy和strcat使用時會有超出字串範圍的風險
解法1:可用assert函式來避免

解法2:strncpy(name,"Oualline",sizeof(name)-1);
           最後一個會自動補'\0'

解法2:strncat(name,"Oualline",sizeof(name)-strlen(name)-1);
           若空間已滿,則'\0'就不會自動加入,需自行填入,
           多寫一行程式碼 name[sizeof(name)-1]='\0';
           加上此行程式碼若未超出空間會多一個'\0',但不影響

2009年9月19日 星期六

C/C++筆記-cstring使用C式字串函式

#include <cstring>
//之後可使用strcpy,strcat,strlen,strcmp...

C/C++筆記-寬字元、寬字串使用

/* 使用L自首來指定寬字元 */
wchar_t wide = L'Ω'; //寬字元使用
wstring hello = L"こんにちは";//寬字串使用

C/C++筆記-at安全取得字串字元

/* 安全取得字串第一個字元(避免字串未定義) */
first_ch = name.at(0); //亦同first_ch = name[0];

C/C++筆記-substr取得部份字串

// 取得字串索引位址第5個字元開始,長度為八個字元
sub_string = main_string.substr(5,8);

C/C++筆記-length取得字串長度

length = full_name.length();

2009年9月12日 星期六

C/C++筆記-代表null的字元

char name[6];
name[0] = 'J';
name[1] = 'a';
name[2] = '\0';
name[3] = 'e';
name[4] = 's';
name[5] = 'm';
printf("%s",name);

畫面只會輸出Ja,讀到'\0'會認定字串已結束
##ShowAll##

C/C++筆記-字串輸入

鍵盤輸入字串常用gets(str)
因為scanf("%s",str)當遇到空格或換行字元便會結束

C/C++筆記-從s1字串中找到s2字串

char *strstr(const char *s1, const char *s2);

C/C++筆記-strrev將字串倒置

strrev(s1); //將s1字串倒置

C/C++筆記-strcpy複製字串

//連同'\0',from字串複製到to字串
strcpy(char *to, const char *from)
strncpy(char *to, const char *from, size_t len)

C/C++筆記-strlen取得字串長度

size_t strlen(const char *str)

C/C++筆記-strcat連結字串

//str1之後接str2
strcat(char *str1, const char *str2)
strncat(char *str1, const char *str2, size_t len)

C/C++筆記-strcmp比較字串

strcmp(const char *str1, const char *str2)
strncmp(const char *str1, const char *str2, size_t len)

/* 相等傳回0,小於傳回負數,大於傳回正數 */

C/C++筆記-strchr尋找字元

strchr(const char *str, int ch)
strrchr(const char *str, int ch)
/