Bootstrap

char 切片/分割 strncpy/strtok

字符串操作 strcpy、strncpy、memmove、memcpy、memset、strlen、strncat 的实现

char 切片

C++ strncpy 函数:

char * strncpy ( char * destination, const char * source, size_t num )

size_t 是无符号整数类型,从源复制的最大字符数

strncpy(sub,char+3,4) // 将char中从3开始的4个数字复制到sub中

strcpy函数中的参数是字符串数组的名字,而数组名本质上是指针,那么,src+3 就可以实现将 src中从第4个字符开始复制n个字符给 dest 了


c++

/*  char 字符串切片截取 strncpy
    比较两个char*字符串是否相等,if(strcmp(recData,name) == 0)来判断
*/

# include<iostream>

using namespace std;

int main () {
	char str1[] = "To be or not to be";
	char str2[40];
	char str3[40];

	/* copy to sized buffer (overflow safe): */
	strncpy ( str2, str1, sizeof(str2) );

	/* partial copy (only 5 chars): */
	strncpy ( str3, str2, 5 );
	str3[5] = '\0';   /* null character manually added */

	puts (str1);
	puts (str2);
	puts (str3);

	cout << "-------" << endl;

	char dest[4] = {""};
	char src[] = {"123456789"};
	strncpy(dest, src, 3);
	puts(dest);

	cout << "-------" << endl;

	char dest1[4] = {""};
	char src1[] = {"123456789"};
	strncpy(dest1, src1 + 3, 3);
	dest[4] = '\0';              //n<sizeof(src)时,必须有这一句,不然输出出错
	puts(dest1);

	return 0;
}


在这里插入图片描述


char 分割

C语言 strtok 函数:

char *strtok(char *str, const char *delim)

strtok函数包含在头文件string.h中,对于char数组可以采用这种方法分割,类似python的split



#include <string.h>
#include <stdio.h>
 
int main(){
    char s[] = "a,b*c,d";
    const char *sep = ",*"; //可按多个字符来分割
    char *p;
    p = strtok(s, sep);
    while(p){
        printf("%s ", p);
        p = strtok(NULL, sep);
    }
    printf("\n");   输出: a b c d
    return 0;
}


输出: a b c d

;