C语言如何实现截取字符串

在C语言中,可以使用库函数和自定义函数来实现字符串的截取。

使用库函数:

  1. 使用字符串库函数strncpy()来实现字符串的截取。该函数的原型为:char *strncpy(char *dest, const char *src, size_t n)。其中,dest为目标字符串,src为源字符串,n为截取的字符个数。 示例代码:

    c 复制代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
       char src[] = "Hello, World!";
       char dest[20];
    
       strncpy(dest, src, 5);
       dest[5] = '\0'; // 添加字符串结束符
       printf("截取的字符串为:%s\n", dest);
    
       return 0;
    }
  2. 使用字符串库函数strtok()来实现字符串的截取。该函数的原型为:char *strtok(char *str, const char *delim)。其中,str为要分割的字符串,delim为分割字符串的分隔符。 示例代码:

    c 复制代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
       char str[] = "Hello, World!";
       char delim[] = " ";
    
       char *token = strtok(str, delim);
       while (token != NULL) {
          printf("%s\n", token);
          token = strtok(NULL, delim);
       }
    
       return 0;
    }

使用自定义函数:

  1. 自定义函数来实现字符串的截取。可以使用指针操作实现字符串的截取。 示例代码:

    c 复制代码
    #include <stdio.h>
    
    void substr(const char *src, char *dest, int start, int length) {
       int i;
       for (i = 0; i < length && src[start + i] != '\0'; i++) {
          dest[i] = src[start + i];
       }
       dest[i] = '\0';
    }
    
    int main() {
       char src[] = "Hello, World!";
       char dest[20];
    
       substr(src, dest, 7, 5);
       printf("截取的字符串为:%s\n", dest);
    
       return 0;
    }

以上是几种常见的字符串截取的方法,可以根据实际需求选择适合的方法来使用。

相关推荐
朝新_27 分钟前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir30 分钟前
Calendar类日期设置进位问题
java·开发语言
木子.李3471 小时前
排序算法总结(C++)
c++·算法·排序算法
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮2 小时前
Python训练第四十三天
开发语言·python
freyazzr3 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++
ascarl20103 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc3 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗4 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长4 小时前
Python 构建法律DeepSeek RAG
开发语言·python