How to use string in c language

下次还敢
Release: 2024-04-27 22:42:16
Original
456 people have browsed it

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>
    Copy after login
  • Initialize string:

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

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

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

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

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>
Copy after login

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!

Related labels:
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