c 语言不输出空数据 (全面覆盖)
目录
去除空值的专栏
- 本文将采用2-3种方式解决空值的问题,实验c语言基本类型,涵盖数组,指针,结构体三种情况
解决方案
一.通过数组的自身性质,让其值大于零
核心代码
if (array[i]>0)
{
// 打印语句
}
1. short 数组测试
源码展示
#define MAXSIZE 20
int main()
{
short ss[MAXSIZE] = {1,2,3,4,5,6};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (ss[i]>0)
{
printf("ss[%d] = %d\n",i,ss[i]);
}
}
}
- 打印结果
错误情况
正确结果
2. int 数组测试
源码展示
#define MAXSIZE 20
int main()
{
int arrary[MAXSIZE] = {1,2,3,4,5,6};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i]>0)
{
printf("arrary[%d] = %d\n", i, arrary[i]);
}
}
}
3. long 数组测试
源码展示
#define MAXSIZE 20
int main()
{
long arrary[MAXSIZE] = {1,2,3,4,5,6};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i]>0)
{
printf("arrary[%d] = %d\n", i, arrary[i]);
}
}
}
4. float 数组测试
源码展示
#define MAXSIZE 20
int main()
{
float arrary[MAXSIZE] = {1.0,2.0,3.0,4.0,5.0,6.0};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i]>0)
{
printf("arrary[%d] = %f\n", i, arrary[i]);
}
}
}
5. float 数组测试
源码展示
#define MAXSIZE 20
int main()
{
double arrary[MAXSIZE] = {1.0,2.0,3.0,4.0,5.0,6.0};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i]>0)
{
printf("arrary[%d] = %f\n", i, arrary[i]);
}
}
}
6. char 数组测试
源码展示
#define MAXSIZE 20
int main()
{
char arrary[MAXSIZE] = {'a','b','c','d','e','f'};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i]>0)
{
printf("arrary[%d] = %c\n", i, arrary[i]);
}
}
}
二.通过字符型数组的最后一位是'\0'过滤(中文的时候,其他类型比如数组,字母符号还是方法一)
核心代码
if (arrary[j] == '\0')
{
break;
}
1.英文
源码展示
#define MAXSIZE 20
int main()
{
char arrary[MAXSIZE] = {'a','b','c','d','e','f'};
int i = 0;
for (i = 0; i < MAXSIZE; i++)
{
if (arrary[i] == '\0')
{
break;
}
printf("arrary[%d] = %c\n", i, arrary[i]);
}
}
2.中文
源码展示
#define MAXSIZE 20
int main()
{
char arrary[MAXSIZE] = {"好好学习天天向上!"};
int i = 0;
int j = 1;
for (i = 0; i <= MAXSIZE; i+=2)
{
if (arrary[i] == '\0')
{
break;
}
if (arrary[i] == '!')
{
printf("arrary[%d] = %c\n", j++, arrary[i]);
}
else {
printf("arrary[%d] = %c%c\n", j++, arrary[i], arrary[i + 1]);
}
}
}
三.指针的方式处理
核心代码
if (*(p + i) == '\0') {
break;
}
实例
#define MAXSIZE 20
int main()
{
char arrary[MAXSIZE] = {"好好学习天天向上!"};
char *p;
p = arrary;
int i = 0;
int j = 1;
for (i = 0; i <= MAXSIZE; i+=2)
{
if (*(p+i) == '\0')
{
break;
}
if (*(p + i) == '!')
{
printf("arrary[%d] = %c\n", j++, *(p + i));
}
else {
printf("arrary[%d] = %c%c\n", j++, *(p + i), *(p + i+1));
}
}
}
其他复杂情况
- 参考
四.while方式处理(最佳)
核心代码
while (*(p + i) != '\0')
{
printf("arrary[%d] = %c%c\n", j++, *(p + i), *(p + i + 1));
i += 2;
}
实例
#define MAXSIZE 20
int main()
{
char arrary[MAXSIZE] = {"好好学习天天向上!"};
char *p;
p = arrary;
int i = 0;
int j = 1;
while (*(p + i) != '\0')
{
if (*(p + i) == '!')
{
printf("arrary[%d] = %c\n", j++, *(p + i));
}
else {
printf("arrary[%d] = %c%c\n", j++, *(p + i), *(p + i + 1));
}
i += 2;
}
}
其他复杂情况
- 参考
十年磨一剑,一剑破万法