Home > Backend Development > C#.Net Tutorial > How to use str in c language

How to use str in c language

下次还敢
Release: 2024-05-09 11:18:20
Original
938 people have browsed it

The str function is a commonly used string processing function in C language. It is used to perform various operations, including: concatenating strings (strcat) comparing strings (strcmp) copying strings (strcpy) and calculating string length. (strlen)

How to use str in c language

Usage of str in C language

Introduction:
str is one of the most commonly used string processing functions in C language. It allows manipulating null-terminated character arrays (strings) and performing various operations.

Syntax:

<code class="c">char *str(const char *str1, const char *str2);</code>
Copy after login

Parameters:

  • str1: The operation to be performed The first string.
  • str2: The second string to perform the operation on.

Return value:
Returns a pointer to the result string.

Usage:
The str function can be used for various string operations, including:

  • String concatenation (strcat): Append str2 to the end of str1.
  • String comparison (strcmp): Compares str1 and str2, returning 0 (equal), a positive integer (str1 is greater than str2), or a negative integer (str1 is less than str2).
  • String copy (strcpy): Copy str2 to str1, overwriting the existing content in str1.
  • String length (strlen): Returns the number of characters in str1 (not including the null terminator).

Example:

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

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

    // 字符串连接
    strcat(str1, " ");
    strcat(str1, str2);
    printf("连接后的字符串:%s\n", str1);

    // 字符串比较
    int result = strcmp(str1, "Hello World");
    if (result == 0) {
        printf("字符串相等\n");
    } else if (result > 0) {
        printf("str1 大于 str2\n");
    } else {
        printf("str1 小于 str2\n");
    }

    // 字符串复制
    strcpy(str1, str2);
    printf("复制后的字符串:%s\n", str1);

    // 字符串长度
    int length = strlen(str1);
    printf("字符串长度:%d\n", length);

    return 0;
}</code>
Copy after login

Output:

<code>连接后的字符串:Hello World
字符串相等
复制后的字符串:World
字符串长度:5</code>
Copy after login

The above is the detailed content of How to use str 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