您现在的位置是:首页 > 学无止境 > C语言网站首页C语言 如何学习C语言、入门C语言,看这篇就够了

如何学习C语言、入门C语言,看这篇就够了

  • 莫愁
  • C语言
  • 2019-11-10
简介该文章将会把C语言基础语法梳理一遍,主要记录帮助理解相关知识点的代码示例和重要或容易忽略的面试知识,将会陆续发布系类文章.
字数 24775

字符与字符串

1.重要的面试题

字符串和字符类型数组的区别是什么?
答:在默认情况下,字符串内存是静态分配的,因此它由NULL初始化.而字符数组的内存不是静态分配的,因此字符数组默认由垃圾数据填充;
两个相同的字符串有相同的内存地址,而两个内容一样的字符数组的内存地址却不一样.

2.重要的面试题

为什么字符串以‘\0’字符作为结尾?
答:字符串在内存中是逐字符顺序存储的,因此,在读取字符串时,需要知道字符串在何处结尾,处于这个目的,编译器会自动在字符串尾部追加‘\0’字符作为字符串结束的标志.

3.重要的面试题

长度为20的字符数组能存储多少个字符?
答:在C语言中,字符串以附加的‘\0’字符结尾,即最后一个字符空间留给‘\0’,所以只能存储19个字符.

3.程序 strcy()与strncpy()

/* 拷贝某字符串的前若干个字符串至s1中*/
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
    char s1[10],s2[50];
    int n;

    puts("Enter a string: ");
    gets(s2);

    puts("How many chars to copy?");
    scanf("%i",&n);
    strncpy(s1, s2, n);
    printf("The first %d chars are:%s",n,s1);
}

输出:

Enter a string:
Nageswara Rao
How many chars to copy?
3
The first 3 chars are: Nag

4.程序 strchr()

// 在字符串中查找指定字符串第一次出现的位置
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
    char str[100],ch;
    char *n;

    printf("Enter a string: ");
    gets(str);
    printf("Enter a character: ");
    ch = getchar();

    n = strchr(str, ch);
    if (n == NULL)
        printf("The character is not found");
    else
        printf("The first occurrence is %d",n-str);
}

输出:

Enter a string: Bottle
Enter a character: t
The first occurrence is 2

5.程序

// 在一个字符串中查找指定字符串首次出现的位置
// 在字符串中查找指定字符串第一次出现的位置
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
    char str[100],sub[20];
    char *n;

    printf("Enter main string: ");
    scanf("%[^\n]",str);
    fflush(stdin);

    printf("Enter sub string: ");
    scanf("%[^\n]",sub);

    n = strstr(str, sub);
    if (n == NULL)
        printf("sub string not found");
    else printf("Sub string is found at position %d",n-str);
}

输出:

Enter main string: This is book
Enter sub string: is
Sub string is found at position 2

6.程序

//  向函数传递一组字符串并在函数内显示它们
// 在字符串中查找指定字符串第一次出现的位置
#include <stdio.h>
#define MAX 50
void myfunction(char arr[MAX][MAX],int n){
    int i;
    for (i = 0; i<n; i++) {
        puts(arr[i]);
    }
}
int main(int argc, const char * argv[]) {
    char str[MAX][MAX];
    int i,n;
    printf("How many strings?");
    scanf("%i",&n);
    fflush(stdin);

    printf("Enter strings: \n");
    for (i = 0; i<n; i++) {
        gets(str[i]);
    }
    printf("Entered strings are: \n");
    myfunction(str, n);

}

 第6页/共11  首页 上一页 4 5 6 下一页 尾页


转载: 感谢您对莫愁个人博客网站平台的认可,非常欢迎各位朋友分享到个人站长或者朋友圈,但转载请说明文章出处“来源莫愁个人博客 https://www.mochoublog.com/study/367.html”。

文章评论

    • 评论
    人参与,条评论

技术在线

服务时间

周一至周日 12:00-22:00

关闭下雪
关闭背景特效