c语言库函数 字符串_C中的字符串(标准库函数)–第4部分

c语言库函数 字符串

Also Read: String in C – Part 3

In the last tutorial I gave a brief introduction of the relation between strings and pointers. I also told you about the 2D array of characters. Today I will tell you about some commonly used standard library string functions. These functions are made by the compiler vendors to speed up the manipulation of strings in C programming. So lets get started.

Standard Library String Functions

There are more than 18 standard library string function but only 4 of them are used very frequently. So I will only discuss those 4 functions which are strlen(), strcpy(), strcat(), strcmp().

Note: The header file that we will use for these functions is string.h.

strlen() in C

As its name suggest, this function is made to calculate the length of the string. By using this function we can calculate the number of characters in any string.


Output

strlen() in C

Explanation
Here you can see I have calculated the length of the string by two ways. So you can either pass string or string variable. Remember while calculating the length it doesn’t count ‘’ character.

strcpy() in C

This function is used to copy contents of one string to another. To use this function we just have to pass the base address of source and target string. Consider the below example.


Output

strcpy() in C

strcat() in C

This string function is used to concatenate (combine) two strings. To use this function we have to pass the base address of the two strings. Consider carefully the below program code.


Output

strcat() in C

strcmp() in C

Do you remember I told you that we can’t compare two strings directly just like common integer variables. This is because it will always give base address of the string to compare. Strcmp() function is used to compare two strings. This function returns 0 if the strings are identical  and returns the difference of ASCII values when a mismatch occurs. Consider the below program carefully.

Output

strcmp() in C

Explanation
In the first call I have compared source string with target string that returns -3 which is numeric difference of their mismatch ASCII characters. In the second call, I have passed two identical strings. Therefore 0 is returned by the function.

翻译自: https://www.thecrazyprogrammer.com/2015/02/string-in-c-standard-library-functions.html

c语言库函数 字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值