C 語言總結 2

2021-10-05 04:31:21 字數 3048 閱讀 2413

c++ 提供了兩種型別的字串表示形式:

c 風格字串

c++ 引入的string型別

int

main()

;//可以簡寫成:

char greeting2=

"hello"

;return0;

}

遍歷字串

字串實際上背後還是乙個陣列,所以可以使用陣列遍歷的手法來獲取每乙個字元

#include

intmain()

}

字串的其他操作

c語言中提供了針對字串操作的大量函式,不過在使用之前,需要先引入#include

以下函式的使用,需要引入#include標頭檔案

函式名

解釋isalpha( c )

如果c是字母,則為真

isalnum( c )

如果c是字母或數字,則為真

isdigit( c )

如果c是數字,則為真

islower( c )

如果c是小寫字母,則為真

isprint( c )

如果c是可列印字元,則為真

ispunct( c )

如果c是標點符號,則為真

isupper( c )

如果c是大寫字母,則為真

isspace( c )

如果c是空格,則為真

返回小寫的c

返回大寫的c

#include

intmain()

需要引入#include,由於string類宣告在命名空間 std ,所以在使用的首要注意 命名空間的聯合使用

//引入string庫

#include

using

namespace std;

intmian()

; string s3

;

string s4 =

"你好"

;

s1 = s3;

return0;

}

拼接字串
直接使用+操作即可

#include

using

namespace std;

intmain()

; string part2

; string sentence ;

sentence = part1 + part2 ;

return0;

}

獲取指定位置的字元
可以使用 [ ] 和 at( ) 操作字串

#include

using

namespace std;

intmain()

; cout << s1[3]

0)<< endl;

return0;

}

遍歷字串
#include

using

namespace std;

intmain()

;for

(char s : s1)

for(

int s : s1)

return0;

}

字串比較
字串可以比較大小的

#include

using

namespace std;

intmain()

; string s2

; string s3

; string s3

; string s3

; s1 == s5 // true

s1 == s2 // false

s1 != s2 // true

s1 < s2 // true

s1 > s2 // false

s1 ==

// false

return0;

}

擷取字串
#include

using

namespace std;

intmain()

; cout << s1.

substr(0

,4);

// this

return0;

}

獲取字元在字串中的索引
rfind : 從右往左找

find : 從左往右找

#include

using

namespace std;

intmain()

; cout << s1.

find

("this");

// 0

cout << s1.

find

("is");

// 2

cout << s1.

find

("test");

// 10

return0;

}

獲取字串長度
str.length() : 返回字串長度

字串中字元替換

str.replace(替換字元的索引,替換長度,替換為什麼字元)

C語言基礎總結2

字元 如下表示 字母或陣列 為字元的表現形式 char a a char b 1 字串char string iphone 字串可理解為字元陣列,表示方法如下 0為結束符 char string 一維陣列 按順序排列的數,用對應下標可找到陣列中對應的內容 陣列中每個元素都是乙個單獨的個體 陣列的表現...

C語言複習總結(2)

c語言的理解。在複習過程中,我發現經過乙個暑假以後,很多語法的細節都記得模糊不清。並且,在我複習函式的時候,發現自己經常容易搞錯格式。值得強調的是在寫迴圈程式時,一定要弄清楚迴圈的條件。並且,對每乙個知識點,都應該立即編出對應的程式,有時可能還會有語法錯誤,碰到更好的方法也可以試一下,很多時候你想想...

c語言知識總結2

一維陣列的定義格式,型別說明符 陣列名 常量表示式 例如 int a 10 c語言中不允許對陣列的大小做動態的定義,即陣列大小不能用變數表示。一維陣列的陣列元素占用的位元組數為4個位元組。幾種錯誤寫法 float a 0 陣列元素大小為0沒有意義 int b 9 不能使用圓括號 int k,a k ...