C语言字符串常用函数学习(一)

memcpy

void * memcpy ( void * destination, const void * source, size_t num );

复制内存

从源source所指内存地址的起始位置开始,复制num个字节到目标destination所指内存地址的起始位置中。

源和目标指针所指向的对象的基本类型是不相关的,结果是数据的二进制副本。

该函数不检查源字符串中的终止符,总是按照num数来复制字节。

为了避免溢出,sourcedestination数组的长度应至少num字节,而且不应重叠(如果重叠的内存块,memmove是一个更安全的方法)。

示例

/* memcpy example */
#include <stdio.h>
#include <string.h>

struct
{
    char name[40];
    int age;
} person, person_copy;

int main ()
{
    char myname[] ="Pierre de Fermat";

    /* using memcpy to copy string: */
    memcpy (person.name, myname, strlen(myname)+1 );
    person.age = 46;
    
    /* using memcpy to copy structure: */
    memcpy ( &person_copy, &person,sizeof(person) );
    
    printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
    return0;
}

执行结果:

person_copy: Pierre de Fermat, 46


memmove

void * memmove ( void * destination, const void * source, size_t num );

移动内存块

source指向的内存位置开始的num字节复制destination指向的内存位置复制发生在中间缓冲区,允许destinationsource重叠。

sourcedestination指针所指向对象的基本类型是不相关的,其结果是数据的二进制副本。

该函数不检查源字符串中的终止符,总是按照num数来复制字节。

为了避免溢出,sourcedestination数组的长度应至少num字节。。

示例

/* memmove example */
#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="memmove can be very useful......";
    memmove(str+20,str+15,11);
    puts(str);
    
    return0;
}

执行结果:

memmove can be very very useful.


strcpy

char * strcpy ( char * destination, const char * source );

复制字符串

复制source指向的字符串到destination指的字符串,包括终止空字符(并在该点停止)。

为了避免溢出,destination数组的大小必须足够长,以容纳source字符串(包括终止空字符),并且在内存上与source不重叠。

示例

/* strcpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
  char str1[]="Sample string";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"copy successful");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}

执行结果:

str1: Sample string
str2: Sample string
str3: copy successful


strncpy

char * strncpy ( char * dest, const char * source, size_t num );

复制字符串字符

复制source字符串的前num个字符到dest字符串,如果source字符串长度小于num,剩下的字节用0x00填充。

如果source字符串长度大于num,dest字符串的末尾就是非空字符,在这种情况下,dest不应被视为空终止字符串,否则读取时会溢出。

sourcedest不应有重叠。

示例

/* strncpy example */
#include <stdio.h>
#include <string.h>
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);
  return 0;
}

执行结果:

To be or not to be
To be or not to be
To be



转载于:https://my.oschina.net/raygo/blog/543087

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值