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;
    }

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

相关推荐
肆忆_13 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星16 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc