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

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

相关推荐
沐怡旸16 分钟前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 小时前
C++ 内存管理
c++
博笙困了7 小时前
AcWing学习——双指针算法
c++·算法
感哥7 小时前
C++ 指针和引用
c++
感哥18 小时前
C++ 多态
c++
沐怡旸1 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4161 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥1 天前
C++ std::set
c++
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
博笙困了1 天前
AcWing学习——差分
c++·算法