这一节主要复习一下字符串,在 C语言中 字符串是由字符数组与空字符\0组成。空字符(Null character)又称结束符,缩写 NUL,是一个数值为 0 的控制字符,\0 是转义字符,意思是告诉编译器,这不是字符 0,而是空字符。1 如何声明一个字符串?如下:
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
数组和字符串是 C 中的二等公民;一旦声明,它们不支持赋值运算符。例如,
char c[100];
c = "C programming"; // Error! array type is not assignable.
注意:使用strcpy() 函数来复制字符串。读取字符串从用户那里
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
输出:
Enter name: Dennis Ritchie
Your name is Dennis.
将字符串传递给函数
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
字符串和指针
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
字符串常见操作:
功能 功能功
strlen() 计算字符串的长度
strcpy() 将一个字符串复制到另一个
strcat() 连接(连接)两个字符串
strcmp() 比较两个字符串
strlwr() 将字符串转换为小写
strupr() 将字符串转换为大写
从用户那里获取字符串输入并显示它
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
删除字符串中除字母以外的字符
#include <stdio.h>
int main() {
char line[150];
printf("Enter a string: ");
fgets(line, sizeof(line), stdin); // take input
for (int i = 0, j; line[i] != '\0'; ++i) {
// enter the loop if the character is not an alphabet
// and not the null character
while (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] == '\0')) {
for (j = i; line[j] != '\0'; ++j) {
// if jth element of line is not an alphabet,
// assign the value of (j+1)th element to the jth element
line[j] = line[j + 1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}
输出:
Enter a string: adf34!sdf^*
Output String: adfsdf