Home > Backend Development > C++ > body text

How to use string.h in c++

下次还敢
Release: 2024-05-08 02:12:17
Original
1045 people have browsed it

Use the string.h header file in C to operate C-style strings, which mainly include the following functions: Copy strings: strcpy(), strncpy() Append strings: strcat(), strncat() Compare characters String: strcmp(), strncmp() Calculate string length: strlen() Initialize memory area: memset()

How to use string.h in c++

string.h in C Usage in

string.h is a header file containing functions for manipulating C-style strings. To use it in C, you need to include this header file first:

<code class="cpp">#include <cstring></code>
Copy after login

The following commonly used functions are provided in string.h:

  • strcpy(): will The source string is copied into the destination string.
  • strncpy(): Copy part of the source string to the target string, the length can be specified.
  • strcat(): Append the source string to the end of the target string.
  • strncat(): Append part of the source string to the end of the target string, the length can be specified.
  • strcmp(): Compares two strings and returns 0 to indicate equality, a positive value indicates that the target string is greater than the source string, and a negative value indicates that the target string is smaller than the source string.
  • strncmp(): Compares the partial contents of two strings, the length can be specified.
  • strlen(): Calculate the length of the string.
  • memset(): Initialize a memory area with a specific value.

Example:

<code class="cpp">#include <cstring>

int main() {
  char str1[] = "Hello";
  char str2[10];

  strcpy(str2, str1);  // 将str1复制到str2
  strcat(str2, " World");  // 追加" World"到str2
  int len = strlen(str2);  // 计算str2的长度

  cout << "str2: " << str2 << endl;
  cout << "Length: " << len << endl;

  return 0;
}</code>
Copy after login

Output:

<code>str2: Hello World
Length: 11</code>
Copy after login

The above is the detailed content of How to use string.h in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!