字符串与字符数组
#include <stdio.h>
#include <string.h>//包含strlen函数
int main(void)
{
printf("size of \"cppcourse\" = %d\n", sizeof("cppcourse"));
printf("length of \"cppcourse\" = %d\n", strlen("cppcourse"));
return 0;
}
字符串变量初始化
二维数组
二维数组初始化
对于一维数组,如果下标越界了,得到的值是不确定的,那对于二维数组呢?
下面以两个实例来操练一下二维数组:
矩阵转置【也就是行变为列,列变为行】
#include <stdio.h>
#define MAX_ROW 2
#define MAX_COL 3
int main(void)
{
int i,j;
int a[MAX_ROW][MAX_COL] = {{1,2,3},{4,5,6}};
int b[MAX_COL][MAX_ROW];
printf("Source:\n");
for(i = 0;i < MAX_ROW;i++)
{
for(j = 0;j < MAX_COL;j++)
{
printf("%4d",a[i][j]);
}
putchar('\n');
}
for(i = 0;i < MAX_ROW;i++)
{
for(j = 0;j < MAX_COL;j++)
{
b[j][i] = a[i][j];
}
}
printf("Result:\n");
for(i = 0;i < MAX_COL;i++)
{ for(j = 0;j < MAX_ROW;j++)
{
printf("%4d",b[i][j]);
}
putchar('\n');
}
return 0;
}
运行结果:
统计C程序关键字个数
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define IN 1
#define OUT 0
//二维字符数组来存放C语言中的所有关键字
char keywords[32][9] = {
"auto", "break", "case", "char",
"const", "continue", "default", "do",
"double", "else", "enum", "extern",
"float", "for", "goto", "if",
"int", "long", "register", "return",
"short", "signed", "sizeof", "static",
"struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while"
};
int main(void)
{
int i, c, state, pos = 0;
state = OUT;
char word[32];//这个是用来存放当前解析的关健字,会不断初始化
int counter[32] = {0};//此变量用来存放关键字出现的次数
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\n' || c=='\t')
{
state = OUT;
word[pos] = '\0';
pos = 0;
for (i=0; i<32; i++)
{
if (strcmp(word, keywords[i]) == 0)
{
counter[i]++;
break;
}
}
}
else if (state == OUT)
{
state = IN;
word[pos++] = c;
}
else
word[pos++] = c;
}
for (i=0; i<32; i++)
{
printf("%-8s:%d\n", keywords[i], counter[i]);
}
return 0;
}
对于空白字符,其实可以用库函数:
#include <stdio.h>
#include <ctype.h>//isspace函数
#include <string.h>
#define IN 1
#define OUT 0
//二维字符数组来存放C语言中的所有关键字
char keywords[32][9] = {
"auto", "break", "case", "char",
"const", "continue", "default", "do",
"double", "else", "enum", "extern",
"float", "for", "goto", "if",
"int", "long", "register", "return",
"short", "signed", "sizeof", "static",
"struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while"
};
int main(void)
{
int i, c, state, pos = 0;
state = OUT;
char word[32];//这个是用来存放当前解析的关健字,会不断初始化
int counter[32] = {0};//此变量用来存放关键字出现的次数
while ((c = getchar()) != EOF)
{
if (isspace(c))//判断一个字符是否是空白字符可以用isspace库函数,需包含ctype.h头
{
state = OUT;
word[pos] = '\0';
pos = 0;
for (i=0; i<32; i++)
{
if (strcmp(word, keywords[i]) == 0)
{
counter[i]++;
break;
}
}
}
else if (state == OUT)
{
state = IN;
word[pos++] = c;
}
else
word[pos++] = c;
}
for (i=0; i<32; i++)
{
printf("%-8s:%d\n", keywords[i], counter[i]);
}
return 0;
}
好了,关于数组就学到这,下个内容再见!!
关注个人公众号,获得实时推送