c語言程式設計(14)

2021-10-01 03:24:49 字數 2857 閱讀 6411

複習

1、 字元陣列

1)輸入、輸出 %s

2)字元陣列初始化 字串

char ch=「hello」

2、字串處理函式

1)函式原型

函式返回值 函式名(形參1型別 形參1,形參2型別 形參2…)

2)函式的呼叫

語法 函式名(實參1,實參2…)

說明:實參必須有確定的值,並且個數和形參保持一致,型別和形參一致或賦值相容 int a=3.6,double x=3;

1、字串輸入、輸出函式

int gets( char * str)====從鍵盤輸入乙個字串,儲存到str所指向的記憶體單元中

int puts(char * str)====輸出str所指向的位址中的字串,並且換行

char ch[20];

gets(ch) ; 等價於 gets(&ch[0]);

gets(ch[1])錯誤,實參型別為char,而函式gets要求的形參型別為char *

gets(&ch[1])正確,從鍵盤輸入乙個字串,儲存到從ch[1]開始的陣列元素

puts(ch);

puts(&ch[1]);正確,輸出從ch[1]開始的乙個字串(到\0之前的字串)

puts(「hello」);

2、字串連線函式

char * strcat(char * str1,char *str2)

將str2所指向的字串,連線到str1所指向的字串後面,並且去掉st1後面的\0,返回的是str1(位址)

注意,str1所指向的記憶體單元足夠大(放下連線後的字串)

char ch1=「hello」;

char ch2=「world」;

strcat(ch1,ch2);錯誤,ch1不足夠大

char ch1[20]=「hello」;

char ch2=「world」;

strcat(ch1,ch2);正確

puts(ch1);輸出helloworld

puts(strcat(ch1,ch2));將strcat(ch1,ch2)函式呼叫的結果(函式的返回值)作為puts的實參,呼叫正確,輸出???

strcat(ch1,&ch2[3]);

puts(ch1);輸出hellold

puts(strcat(ch1,&ch2[3]));輸出????

strcat(&ch1[2],ch2);

puts(ch1);輸出 helloworld ???

puts(strcat(&ch1[2],ch2));輸出 ?????

3、字串複製函式

1)函式原型

char * strcpy(char * str1,char *str2)

把str2指向的字串複製到str1所指向的記憶體單元中,返回str1(位址)

注意,str1所指向的記憶體單元大小要大於等於str2所指向的記憶體單元大小

char ch1[20]=「hello」;

char ch2=「wor」;

strcpy(ch1,ch2);

puts(ch1);輸出wor

strcpy(「hello」,「worldddd」);錯誤,第乙個引數的記憶體空間不足夠大

puts(strcpy(ch1,ch2));輸出wor

strcpy(&ch1[1],&ch2[1]);

puts(ch1);輸出hor

puts(strcpy(&ch1[1],&ch2[1]))輸出or等價於 strcpy(&ch1[1],&ch2[1]);puts(&ch1[1]);

函式原型

char * strncpy(char * str1,char *str2,int n);

把str2指向的字串中的n個字元(不一定包含\0)複製到str1所指向的記憶體單元中,返回str1(位址)

char ch1[20]=「hello」;

char ch2=「world」;

strncpy(ch1,ch2,3);

puts(ch1);//輸出worlo

4、字串比較函式

函式原型

int strcmp(char *str1,char * str2)

比較兩個字串的大小(逐個字元比較ascii值的大小),如果str1>str2返回1,如果str1=str2返回0,如果str15、字串有效長度函式

函式原型

unsigned int strlen(char *str)

統計str字串中字元的個數,不包括\0,返回字元個數

char ch1[20]=「hello」;

char ch2=「world」;

int a,b,c;

a=strlen(ch1); 5

b=strlen(ch2); 5

c=strlen(「wordl」); 5

6、字串轉換小寫

strlwr(char * str)

char ch1=「hello」

strlwr(ch1)//hello

7、字串轉換成大寫

strupr(char *str)

char ch1=「hello」

strupr(ch1); //hello

第七章 函式(實現了一定功能的**模組)-模組化,**復用

1、函式的定義

語法函式返回值型別 函式名(形參1型別 形參1,形參2型別 形參2…)//函式的首部

int f=add(2,3);

int add()

{int x,y,z;

scanf("%d%d",&x,&y);

z=x+y;

return z;

int f=add();

2、函式的呼叫

3、函式的宣告(函式原型宣告)

C語言程式設計(14)

題目 將乙個正整數分解質因數。例如 輸入90,列印出90 2 3 3 5。程式分析 對n進行分解質因數,應先找到乙個最小的質數k,然後按下述步驟完成 1 如果這個質數恰等於n,則說明分解質因數的過程已經結束,列印出即可。2 如果n k,但n能被k整除,則應列印出k的值,並用n除以k的商,作為新的正整...

《c程式語言》讀書筆記(一)1 4

自己的一些思考 1 printf和getchar的區別 scanf printf 可以輸入輸出各種型別的變數,比如int float char,而且同時輸入 輸出多個也可以 如scanf d,d a,b getchar putchar 只能輸入輸出char型別的變數,而且只能同時輸入輸出乙個字元 s...

關鍵詞 C語言程式設計(1 4章)

組合語言 缺少可移植性 安全性,穩定性,易於維護 c較其他語言不具有的 需求分析 設計 編寫程式 除錯程式 gcc編譯器,gdb偵錯程式 unix linux平台的主流,window也可以用 無符號整形常量 30u 30u非法 長整型常量 1024l eg.無符號長整型常量 lu 指數形式 3.45...