Home >Backend Development >C++ >How to use string in c language

How to use string in c language

下次还敢
下次还敢Original
2024-04-29 20:33:19497browse

A string is represented in C language as a null-terminated character array. Strings can be created through literals or using the malloc() function; characters can be accessed through the [] operator, but strings are immutable and need to be modified using functions such as strcpy(); in addition, there are multiple string manipulation functions, such as strchr () and strtok() are used to find characters and decompose strings.

How to use string in c language

Usage of string in C language

What is string?

string is a data type representing text strings in C language. It is a null character ('\0') terminated character array.

Create string

There are two main ways to create a string:

  • Literal definition:

    <code class="c">char s[] = "Hello World";</code>
  • Use malloc() function to allocate memory:

    <code class="c">char *s = (char *) malloc(length + 1);
    strcpy(s, "Hello World");</code>

Access characters in string

You can use the character array index operator [] to access a single character in a string:

<code class="c">printf("%c", s[0]); // 输出 'H'</code>

Modify string

string in C language is Immutable. To modify a string, you must use the following function:

  • strcpy(): Copy one string to another string.
  • strcat(): Concatenate two strings together.
  • strlen(): Get the length of string (excluding null characters).
  • strcmp(): Compare the values ​​of two strings.

String operation functions

There are other string operation functions in the C language, such as:

  • strchr(): Find specific characters in string.
  • strtok(): Decompose a string into substrings (tokens).
  • sprintf(): Format string and write it to buffer.

Example

The following code snippet demonstrates the use of string in C language:

<code class="c">#include <stdio.h>
#include <string.h>

int main() {
    // 创建一个 string
    char s[] = "Hello World";

    // 打印 string 的长度
    printf("String length: %d\n", strlen(s));

    // 修改 string
    strcpy(s, "Goodbye World");

    // 打印修改后的 string
    printf("Modified string: %s\n", s);

    return 0;
}</code>

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

Statement:
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