Home  >  Article  >  Backend Development  >  How to use string in c language

How to use string in c language

下次还敢
下次还敢Original
2024-04-27 22:42:16455browse

In C language, string ends with '\0', which is used to store and process strings. Specific usages include: declare string: char string_name[size]; initialize string: char string_name[] = "content"; access element: string_name[index]; obtain length: strlen(string_name); compare string: strcmp(string1, string2) ;String function: strlen() returns length, strcmp() compares, strcpy() copies, strcat() appends.

How to use string in c language

Usage of string in C language

string is used to store and process strings in C language Character array. It is terminated with '\0' (null character) to indicate the end of the string.

Usage of string

  • Declare string:

    <code class="C">char string_name[size];</code>
  • Initialize string:

    <code class="C">char string_name[] = "Hello World";</code>
  • Access string element:

    <code class="C">string_name[index];</code>
  • ##Get the string length :

    <code class="C">strlen(string_name);</code>
  • Compare strings:

    <code class="C">strcmp(string1, string2);</code>

string function

C language provides the following string functions:

  • strlen(): Returns the string length.
  • strcmp(): Compares two strings and returns 0 for equality, otherwise a non-zero value is returned.
  • strcpy(): Copy one string to another string.
  • strcat(): Appends one string to another string.

string example

<code class="C">#include <stdio.h>

int main() {
    char string1[] = "Hello";
    char string2[] = "World";

    printf("%s\n", string1);  // 输出:Hello
    printf("%d\n", strlen(string1));  // 输出:5

    strcpy(string2, string1);  // 将string1复制到string2
    printf("%s\n", string2);  // 输出:Hello

    strcat(string2, "!");  // 将"!"附加到string2
    printf("%s\n", string2);  // 输出:Hello!

    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