std::strcpy、strncpy、memset、memcpy用法

转载自:https://blog.csdn.net/jin13277480598/article/details/53542209

1. std::strcpy

功能:将一个字符串复制到另一个字符串(如果字符串重叠,该行为是未定义);
定义于头文件 <cstring>

 char *strcpy( char *dest, const char *src );

参数:

dest :指向复制内容存放的首地址
src :需要被复制的C风格的字符串
返回值 :复制后的字符串的首地址

Example:

/* strcpy example */
#include <iostream>
 #include <cstring>
 using namespace std;
  int main ()
  {
    char str1[]= "Sample string";
    char str2[40];
    char str3[40];
   strcpy (str2,str1);
   strcpy (str3,"copy successful");

   cout<<"str1:"<<str1<<endl;
   cout<<"str2:"<<str2<<endl;
   cout<<"str3:"<<str3<<endl;

   return 0;
 }

Output:

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

2.std::strncpy

定义于头文件<cstring>

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

功能:将一个字符串的一部分复制到另一个字符串;
说明:从原地址source开始,复制num个字符到dest开始的地址;

说明:从源地址source开始,复制num个字符到dest开始的地址

Example

C版:

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

Output:

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

C++:

#include <iostream>
#include <cstring>

int main()
{
    const char* src = "hi";
    char dest[6] = {'a', 'b', 'c', 'd', 'e', 'f'};;
    std::strncpy(dest, src, 5);
 //多出的用空字符填充
    std::cout << "The contents of dest are: ";
    for (char c : dest) {
        if (c) {
            std::cout << c << ' ';
        } else {
            std::cout << "\\0" << ' ';
        }
    }
    std::cout << '\n';
    return 0;
}
output:

The contents of dest are: h i \0 \0 \0 f

3.std::memcpy

定义于头文件 <cstring>

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

功能:将一个缓冲区复制到另一个缓冲区;

Example

#include <iostream>
#include <cstring>

int main()
{
    char source[] = "once upon a midnight dreary...";
    char dest[4];
    std::memcpy(dest, source, sizeof dest);
    for (char c : dest) {
        std::cout << c << '\n';
    }
    return 0;
} 

output:
o
n
c
e

4.std::memset

定义于头文件 <cstring>

void * memset ( void * ptr, int value, size_t num );

功能:将指针ptr所指向的内存空间开始的num个内存单元设置成value的值;

参数:

ptr:指向要设置值的内存块

value:要填充的值

num:要填充的大小

C:

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

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

Output:

—— every programmer should know memset!

C++版:

#include <iostream>
#include <cstring>

int main()
{
    int a[20];
    std::memset(a, 0, sizeof(a));
    std::cout << "a[0] = " << a[0] << '\n';
    return 0;
}
output:
a[0]=0

猜你喜欢

转载自blog.csdn.net/qiana_/article/details/79978075