Home >Backend Development >C#.Net Tutorial >Usage of string in c language

Usage of string in c language

下次还敢
下次还敢Original
2024-05-09 12:24:21495browse

Strings in the C language are stored as null-terminated character arrays. Its characters can be accessed via subscripts, using strlen() to find the length. String operations include input/output, comparison, copying, concatenation, and searching. The sample code demonstrates operations such as access, length, copy, and search.

Usage of string in c language

String in C language

In C language, a string is a null-terminated character array.

Use of string

  • Declare string: char str[] = "Hello World";
  • Access string characters: str[i], where i is the index of the character in the string.
  • String length: Use the strlen() function.

String operations

Input and output:

  • Input string: gets() or scanf()
  • Output string: puts() or printf()

Comparison:

  • String equality: strcmp(str1, str2) == 0
  • Strings are not equal: strcmp(str1, str2) != 0

##Copy:

  • Copy string: strcpy(destination, source)
  • Safe copy: strncpy(destination, source, n)

Splicing:

  • String splicing: strcat(str1, str2)

Search:

  • The position where the character appears in the string: strchr(str, ch)
  • The position where the substring appears in the string: strstr(str, sub)
Example

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

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

    // 访问字符串字符
    printf("第一个字符:%c\n", str[0]);

    // 字符串长度
    printf("字符串长度:%d\n", strlen(str));

    // 字符串比较
    if (strcmp(str, "Hello World") == 0) {
        printf("字符串相等\n");
    }

    // 字符串复制
    char copy[20];
    strcpy(copy, str);

    // 字符串拼接
    strcat(str, "! Welcome");

    // 字符串搜索
    char* pos = strchr(str, '!');
    if (pos) {
        printf("感叹号的位置:%d\n", pos - str);
    }

    return 0;
}</code>

Output:

<code>第一个字符:H
字符串长度:11
字符串相等
Hello World! Welcome
感叹号的位置:11</code>

The above is the detailed content of Usage of 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