如何从c中的较大字符串中获取子字符串?

时间:2014-01-22 19:49:07

标签: c string substring

在java中我们可以使用

sting_name.substring(start, end); 

获取新的子字符串

    String full_line = "this is a simple line.";
    String part_line;
    System.out.println(full_line);
    part_line = full_line.substring(10, 16);
    System.out.println(part_line);

如何在c中做同样的事情?有没有类似于substring的函数?

char full_line[] = "this is a simple line" ;
char part_line[20];
printf("\n%s\n",full_line);
//part_line ;

2 个答案:

答案 0 :(得分:0)

使用strncpy

实施例

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

int main()
{
   char src[40];
   char dest[12];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strncpy(dest, src+2, 10);

   printf("Final copied string : %s\n", dest);

   return(0);
}

答案 1 :(得分:0)

Get a substring of a char*

看了上面的链接我试过这个: 只是想确定这是否是这样做的正确方法还是存在缺点?

char full_line[] = "this is a simple line" ;
char part_line[20];
printf("\n%s\n",full_line);
memcpy( part_line, &full_line[10], 6);
part_line[6+1] = '\0';
printf("\n%s\n",part_line);