随笔

测字符串长度的几种方法:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char str[]="China";
    printf("%d",strlen(str));
    system("pause");
    return 0;
}

运行结果为:5
这种方法运用了strlen函数,这需要把string.h文件包含到头文件中。

 

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char str[]="China";
    printf("%d",sizeof(str));
    system("pause");
    return 0;
}

运行结果为:6
这种方法就不需要string.h文件,但却会把字符串结束标志'\0'计算在内,无法计算字符串的实际长度。

sizeof 是求字节数运算符

如果将第四行改为  char str[10]="Cina"; 那么运行结果将会为 10。

 

 

输入数组:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int a[ ]={1,2,3,4,5};
    printf("%d",sizeof(a)/sizeof(int));
    system("pause");
    return 0;
}

运行结果为:5
若将第六行改为 printf("%d",sizeof(a));  则运行结果为  20;因为 int(基本整型)的字节数为 4。

 

#include <stdio.h>
#include<stdlib.h>
int main()
{
    int i, j, N = 5;
    for (i = -N;i <= N;i++)
    {
        for (j = -N;j <= N;j++)
        {
            if (abs(j) <= N - abs(i))
                putchar('A' + N - abs(j) - abs(i));
            else
                putchar(' ');
        }
        putchar('\n');
    }
    system("pause");
    return 0;
}

运行结果为:               A

                                  ABA

                                ABCBA

                              ABCDCBA

                           ABCDEDCBA

                         ABCDEFEDCBA

                           ABCDEDCBA

                              ABCDCBA

                                 ABCBA

                                    ABA

                                      A

 

posted @ 2018-11-29 00:06  YTHLW  阅读(137)  评论(0编辑  收藏  举报