C语言入门小册子
字符串函数库
字符串函数库需要以下声明:
#include <string.h>
以下是一些最常用的字符串函数:
strlen()
:获取字符串的长度。strcpy()
:将一个字符串复制到另一个字符串。strcat()
:将两个字符串连接在一起(拼接)。strcmp()
:比较两个字符串。strchr()
:在字符串中查找字符。strstr()
:在字符串中查找子字符串。strlwr()
:将字符串转换为小写字母。strupr()
:将字符串转换为大写字母。
strlen()
strlen()
函数返回字符串的长度,不包括结尾的 NUL 字符。例如:
/* strlen.c */
#include <stdio.h>
#include <string.h>
int main()
{
char *t = "XXX";
printf("Length of <%s> is %d.\n", t, strlen(t));
}
该程序输出:
Length of <XXX> is 3.
strcpy()
strcpy()
函数用于将一个字符串复制到另一个字符串。例如:
/* strcpy.c */
#include <stdio.h>
#include <string.h>
int main()
{
char s1[100], s2[100];
strcpy(s1, "xxxxxx 1");
strcpy(s2, "zzzzzz 2");
puts("Original strings:");
puts("");
puts(s1);
puts(s2);
puts("");
strcpy(s2, s1);
puts("New strings:");
puts("");
puts(s1);
puts(s2);
}
该程序输出:
Original strings:
xxxxxx 1
zzzzzz 2
New strings:
xxxxxx 1
xxxxxx 1
需要注意的两个要点:
- 这个程序假设
s2
有足够的空间来存储最终的字符串。strcpy()
不会检查这一点,如果s2
空间不足,会导致错误。 - 字符串常量可以作为源字符串使用,但作为目标字符串使用时没有意义。这些注意事项同样适用于大多数其他字符串函数。
strncpy()
strncpy()
是 strcpy()
的变种,用于复制源字符串中的前 n
个字符到目标字符串,前提是源字符串至少有 n
个字符。例如,如果修改程序为:
strncpy(s2, s1, 5);
则输出结果会变为:
New strings:
xxxxxx 1
xxxxxz 2
请注意,参数 n
的类型是 size_t
,它在 string.h
中定义。由于前 5 个字符中没有 NUL 字符,strncpy()
在复制后不会自动添加 \0
。
strcat()
strcat()
函数用于连接两个字符串:
/* strcat.c */
#include <stdio.h>
#include <string.h>
int main()
{
char s1[50], s2[50];
strcpy(s1, "Tweedledee ");
strcpy(s2, "Tweedledum");
strcat(s1, s2);
puts(s1);
}
这将把 s2
连接到 s1
的末尾,输出:
Tweedledee Tweedledum
strncat()
strncat()
是 strcat()
的变种,它将源字符串中的前 n
个字符追加到目标字符串末尾。如果在上面的示例中使用 strncat()
且长度为 7:
strncat(s1, s2, 7);
结果将是:
Tweedledee Tweedle
同样,长度参数的类型是 size_t
。
strcmp()
strcmp()
函数用于比较两个字符串:
/* strcmp.c */
#include <stdio.h>
#include <string.h>
#define ANSWER "blue"
int main()
{
char t[100];
puts("What is the secret color?");
gets(t);
while (strcmp(t, ANSWER) != 0)
{
puts("Wrong, try again.");
gets(t);
}
puts("Right!");
}
strcmp()
函数在比较成功时返回 0,否则返回非零值。比较是区分大小写的,因此回答 "BLUE" 或 "Blue" 是不行的。
strcmp()
还有三种变体形式:
strncmp()
:比较源字符串和目标字符串的前n
个字符,例如strncmp(s1, s2, 6)
。stricmp()
:忽略大小写的字符串比较。strnicmp()
:忽略大小写的strncmp
函数。
strchr()
strchr()
函数用于查找字符串中首次出现的指定字符。如果找到该字符,它返回一个指向该字符的指针,否则返回 NULL
。例如:
/* strchr.c */
#include <stdio.h>
#include <string.h>
int main()
{
char *t = "MEAS:VOLT:DC?";
char *p;
p = t;
puts(p);
while((p = strchr(p, ':')) != NULL)
{
puts(++p);
}
}
该程序输出:
MEAS:VOLT:DC?
VOLT:DC?
DC?
字符被定义为字符常量,C 语言将其视为 int
。注意程序中如何在使用指针前递增它(++p
),使得它指向 :
后面的字符,而不是 :
本身。
strrchr()
strrchr()
函数几乎与 strchr()
相同,不同之处在于它查找字符串中最后一次出现的字符。
strstr()
strstr()
函数与 strchr()
类似,只不过它查找的是一个子字符串,而不是单个字符。它同样返回一个指针。例如:
char *s = "Black White Brown Blue Green";
...
puts(strstr(s, "Blue"));
strlwr()
和 strupr()
strlwr()
和 strupr()
函数分别将源字符串转换为小写或大写字母。例如:
/* casecvt.c */
#include <stdio.h>
#include <string.h>
int main()
{
char *t = "Hey Barney hey!";
puts(strlwr(t));
puts(strupr(t));
}
输出将是:
hey barney hey!
HEY BARNEY HEY!
这两个函数只在某些编译器中实现,并不是 ANSI C 的一部分。