C语言字符串操作

1.字符串连接

#include <stdint.h>
#include <string.h>
#include <stdio.h>

int main() {

    char * str = "Hello";
    char * str1 = "World";
    const uint32_t DIST_LEN = 100;
    char dist[DIST_LEN];
    memset(dist, 0, DIST_LEN);

    strcat(dist,str);
    strcat(dist," ");
//    strcat(dist,str1);
    strncat(dist,str1,4);//仅连接指定长度
    puts(dist);
    return 0;
}


2.格式化字符串

#include <stdio.h>
#include <string.h>

int main() {
    //合
    char * str = "Item";
    int a = 100;
    float b = 3.14;
    char dist[100];
    memset(dist, 0, 100);
    sprintf(dist, "%s %d,MATH_PI = %.2f", str, a, b);
    puts(dist);

    //分
    char * string = "Item 100";
    char buf[10];
    memset(buf,0,10);
    int c;
    sscanf(string,"%4s %d",buf,&c);
    printf("String is %s,and int value is %d.\n",buf,a);
    return 0;
}


3.字符串与基础数据类型转换

#include <stdio.h>
#include <stdlib.h>

int main() {
    //char-->int
    char *str = "100";
    int a;
    sscanf(str, "%d", &a);
    printf("Int value is %d.\n", a);

    //char-->double
    double value = atof("3.14");
    printf("%.2f\n", value);

    //int-->char
    int b = 1000;
    char buf[10];
    sprintf(buf, "%d", b);
    puts(buf);

    return 0;
}


4.字符串比较

#include <stdio.h>
#include <string.h>

int main() {

    char *str = "hello";
    char *str1 = "hello";
    printf("Result is %d\n", str == str1);// == 表示测试的是*地址*
    char str2[] = "hello";
    printf("Result is %d\n", str == str2);

    //地址
    printf("Pointer str %p,Pointer str1 %p,Pointer str2 %p\n", str, str1, str2);

    //比较字符串的值 strcmp 比较的是值 *内容*一样的就是0
    int result = strcmp(str, str2);
    if (result == 0) {
        puts("Two string is equal");
    } else {
        puts("Two string not equal");
    }
    return 0;
}


5.字符串的截取

#include <string.h>
#include <stdio.h>


int main() {

    char *str = "Hello World";
    puts(str);
    char *str1 = strchr(str, 'o');//截取从前面开始o的后面的内容,含有o
    puts(str1);
    char *str2 = strrchr(str, 'o');//截取从后面开始o的后面的内容,含有o
    puts(str2);
    char *str3 = strstr(str, "Wo");//截取wo后面的内容,含有wo
    puts(str3);

    char str4[10];
    memset(str4, 0, 10);
    strncpy(str4, str, 4);//截取从开始开始到第四个字符
    puts(str4);

    char *str5 = str + 3;//截取第3个字符往后的内容。不含有第5个字符
    puts(str5);

    //截取第4位之后,4---9位(含)之间的内容
    char *temp = str + 4;
    char str6[10];
    memset(str6, 0, 10);
    strncpy(str6, temp, 5);
    puts(str6);

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值