string.h

字符串

Overview

Drawing
https://www.runoob.com/ [1]
  1. 字符串 = 真正的字符串内容+'\0','\0'用来代表字符串结束。

  2. scanf 和printf用 %s 占位字符串

Functions

I
函数 & 描述

1

void *memchr(const void *str, int c, size_t n) 在参数 str 所指向的字符串的前 n 个字节中搜索第一次出现字符 c(一个无符号字符)的位置。

2

int memcmp(const void *str1, const void *str2, size_t n)str1str2 的前 n 个字节进行比较。

3

void *memcpy(void *dest, const void *src, size_t n) 从 src 复制 n 个字符到 dest

4

void *memmove(void *dest, const void *src, size_t n) 另一个用于从 src 复制 n 个字符到 dest 的函数。

5

void *memset(void *str, int c, size_t n) 将指定的值 c 复制到 str 所指向的内存区域的前 n 个字节中。

6

char *strcat(char *dest, const char *src)src 所指向的字符串追加到 dest 所指向的字符串的结尾。

7

char *strncat(char *dest, const char *src, size_t n)src 所指向的字符串追加到 dest 所指向的字符串的结尾,直到 n 字符长度为止。

8

char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。

9

int strcmp(const char *str1, const char *str2)str1 所指向的字符串和 str2 所指向的字符串进行比较。

10

int strncmp(const char *str1, const char *str2, size_t n)str1str2 进行比较,最多比较前 n 个字节。

11

int strcoll(const char *str1, const char *str2)str1str2 进行比较,结果取决于 LC_COLLATE 的位置设置。

12

char *strcpy(char *dest, const char *src) 【不检查空间】把 src 所指向的字符串复制到 dest

13

char *strncpy(char *dest, const char *src, size_t n) 【会限制空间】把 src 所指向的字符串复制到 dest,最多复制 n 个字符。

14

size_t strcspn(const char *str1, const char *str2) 检索字符串 str1 开头连续有几个字符都不含字符串 str2 中的字符。

15

char *strerror(int errnum) 从内部数组中搜索错误号 errnum,并返回一个指向错误消息字符串的指针。

16

size_t strlen(const char *str) 计算字符串 str 的长度,直到空结束字符,但不包括空结束字符。

17

char *strpbrk(const char *str1, const char *str2) 检索字符串 str1 中第一个匹配字符串 str2 中字符的字符,不包含空结束字符。也就是说,依次检验字符串 str1 中的字符,当被检验字符在字符串 str2 中也包含时,则停止检验,并返回该字符位置。

18

char *strrchr(const char *str, int c) 在参数 str 所指向的字符串中搜索最后一次出现字符 c(一个无符号字符)的位置。

19

size_t strspn(const char *str1, const char *str2) 检索字符串 str1 中第一个不在字符串 str2 中出现的字符下标。

20

char *strstr(const char *haystack, const char *needle) 在字符串 haystack 中查找第一次出现字符串 needle(不包含空结束字符)的位置。

21

char *strtok(char *str, const char *delim) 分解字符串 str 为一组字符串,delim 为分隔符。

22

size_t strxfrm(char *dest, const char *src, size_t n) 根据程序当前的区域选项中的 LC_COLLATE 来转换字符串 src 的前 n 个字符,并把它们放置在字符串 dest 中。

strlen

strlen 通过检查'\0'判断长度

可以把字符串中的某一位变成'\0'来提前截断字符串

/* test_fit.c -- try the string-shrinking function */
#include <stdio.h>
#include <string.h> /* contains string function prototypes */
void fit(char *, unsigned int);

int main(void)
{
    char mesg[] = "Things should be as simple as possible,"
                  " but not simpler.";

    puts(mesg);
    fit(mesg, 38);
    puts(mesg);
    puts("Let's look at some more of the string.");
    puts(mesg + 39);

    return 0;
}

void fit(char *string, unsigned int size)
{
    if (strlen(string) > size)
        string[size] = '\0';
}

// (base) kimshan@MacBook-Pro output % ./"test_fit"
// Things should be as simple as possible, but not simpler.
// Things should be as simple as possible
// Let's look at some more of the string.
//  but not simpler.
strcat

把第二个拼在第一个后边

/* str_cat.c -- joins two strings */
#include <stdio.h>
#include <string.h> /* declares the strcat() function */
#define SIZE 80
char *s_gets(char *st, int n);
int main(void)
{
    char flower[SIZE];
    char addon[] = "s smell like old shoes.";

    puts("What is your favorite flower?");
    if (s_gets(flower, SIZE))
    {
        strcat(flower, addon);
        puts(flower);
        puts(addon);
    }
    else
        puts("End of file encountered!");
    puts("bye");

    return 0;
}

char *s_gets(char *st, int n)
{
    char *ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else // must have words[i] == '\0'
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

// (base) kimshan@MacBook-Pro output % ./"str_cat"
// What is your favorite flower?
// sunflower
// sunflowers smell like old shoes.
// s smell like old shoes.
// bye
strncat

strcat 无法检查第一个数组是否能容纳第二个数组,如果数组 1 不够大,就会溢出影响旁边存储的内容!

/* join_chk.c -- joins two strings, check size first */
#include <stdio.h>
#include <string.h>
#define SIZE 30
#define BUGSIZE 13
char *s_gets(char *st, int n);
int main(void)
{
    char flower[SIZE];
    char addon[] = "s smell like old shoes.";
    char bug[BUGSIZE];
    int available;

    puts("What is your favorite flower?");
    s_gets(flower, SIZE);
    if ((strlen(addon) + strlen(flower) + 1) <= SIZE)
        strcat(flower, addon);
    puts(flower);
    puts("What is your favorite bug?");
    s_gets(bug, BUGSIZE);
    available = BUGSIZE - strlen(bug) - 1;
    strncat(bug, addon, available);
    puts(bug);

    return 0;
}
char *s_gets(char *st, int n)
{
    char *ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else // must have words[i] == '\0'
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

// (base) kimshan@MacBook-Pro output % ./"join_chk"
// What is your favorite flower?
// 1123456789098765432134567890
// 1123456789098765432134567890
// What is your favorite bug?
// qwertyuiokjhgfdscvvbnm
// qwertyuiokjh
// (base) kimshan@MacBook-Pro output % ./"join_chk"
// What is your favorite flower?
// sunflower
// sunflower
// What is your favorite bug?
// overflow
// overflows sm
// (base) kimshan@MacBook-Pro output % ./"join_chk"
// What is your favorite flower?
// 1
// 1s smell like old shoes.
// What is your favorite bug?
// 2
// 2s smell lik
strcmp

进行字符串比较

/* compback.c -- strcmp returns */
#include <stdio.h>
#include <string.h>
int main(void)
{
    
    printf("strcmp(\"A\", \"A\") is ");
    printf("%d\n", strcmp("A", "A"));
    
    printf("strcmp(\"A\", \"B\") is ");
    printf("%d\n", strcmp("A", "B"));
    
    printf("strcmp(\"B\", \"A\") is ");
    printf("%d\n", strcmp("B", "A"));
    
    printf("strcmp(\"C\", \"A\") is ");
    printf("%d\n", strcmp("C", "A"));
    
    printf("strcmp(\"Z\", \"a\") is ");
    printf("%d\n", strcmp("Z", "a"));
    
    printf("strcmp(\"apples\", \"apple\") is ");
    printf("%d\n", strcmp("apples", "apple"));
    
    return 0;
}

// (base) kimshan@MacBook-Pro output % ./"compback"
// strcmp("A", "A") is 0
// strcmp("A", "B") is -1
// strcmp("B", "A") is 1
// strcmp("C", "A") is 1
// strcmp("Z", "a") is -1
// strcmp("apples", "apple") is 1
strncmp

限定找前n 个字符

/* starsrch.c -- use strncmp() */
#include <stdio.h>
#include <string.h>
#define LISTSIZE 6
int main()
{
    const char *list[LISTSIZE] = {
        "astronomy",
        "astounding",
        "astrophysics",
        "ostracize",
        "asterism",
        "astrophobia",
    };
    int count = 0;
    int i;

    for (i = 0; i < LISTSIZE; i++)
        if (strncmp(list[i], "astro", 5) == 0)
        {
            printf("Found: %s\n", list[i]);
            count++;
        }
    printf("The list contained %d words beginning"
           " with astro.\n",
           count);

    return 0;
}

// (base) kimshan@MacBook-Pro output % ./"starsrch"
// Found: astronomy
// Found: astrophysics
// Found: astrophobia
// The list contained 3 words beginning with astro.
strcpy

字符串拷贝

/* copy1.c -- strcpy() demo */
#include <stdio.h>
#include <string.h> // declares strcpy()
#define SIZE 40
#define LIM 5
char *s_gets(char *st, int n);

int main(void)
{
    char qwords[LIM][SIZE];
    char temp[SIZE];
    int i = 0;

    printf("Enter %d words beginning with q:\n", LIM);
    while (i < LIM && s_gets(temp, SIZE))
    {
        if (temp[0] != 'q')
            printf("%s doesn't begin with q!\n", temp);
        else
        {
            strcpy(qwords[i], temp);
            i++;
        }
    }
    puts("Here are the words accepted:");
    for (i = 0; i < LIM; i++)
        puts(qwords[i]);

    return 0;
}

char *s_gets(char *st, int n)
{
    char *ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else // must have words[i] == '\0'
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

// (base) kimshan@MacBook-Pro output % ./"copy1"
// Enter 5 words beginning with q:
// qwert
// qazwsx
// qwererty
// qqq
// q
// Here are the words accepted:
// qwert
// qazwsx
// qwererty
// qqq
// q
strcpy

因为第一个参数是指针,所以我们可以从某个位置开始加入新字符。

/* copy2.c -- strcpy() demo */
#include <stdio.h>
#include <string.h> // declares strcpy()
#define WORDS "beast"
#define SIZE 40

int main(void)
{
    const char *orig = WORDS;
    char copy[SIZE] = "Be the best that you can be.";
    char *ps;

    puts(orig);
    puts(copy);
    ps = strcpy(copy + 7, orig);
    puts(copy);
    puts(ps);

    return 0;
}

// (base) kimshan@MacBook-Pro output % ./"copy2"
// beast
// Be the best that you can be.
// Be the beast
// beast
strncpy
/* copy3.c -- strncpy() demo */
#include <stdio.h>
#include <string.h> /* declares strncpy() */
#define SIZE 40
#define TARGSIZE 7
#define LIM 5
char *s_gets(char *st, int n);

int main(void)
{
    char qwords[LIM][TARGSIZE];
    char temp[SIZE];
    int i = 0;

    printf("Enter %d words beginning with q:\n", LIM);
    while (i < LIM && s_gets(temp, SIZE))
    {
        if (temp[0] != 'q')
            printf("%s doesn't begin with q!\n", temp);
        else
        {
            strncpy(qwords[i], temp, TARGSIZE - 1);
            qwords[i][TARGSIZE - 1] = '\0';
            i++;
        }
    }
    puts("Here are the words accepted:");
    for (i = 0; i < LIM; i++)
        puts(qwords[i]);

    return 0;
}

char *s_gets(char *st, int n)
{
    char *ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else // must have words[i] == '\0'
            while (getchar() != '\n')
                continue;
    }
    return ret_val;
}

// (base) kimshan@MacBook-Pro output % ./"copy3"
// Enter 5 words beginning with q:
// q1
// q12
// q12345
// q1234567
// q1234567890
// Here are the words accepted:
// q1
// q12
// q12345
// q12345
// q12345

Content in Table

has C++ demo links[2]

Copying - function
Description

Copy block of memory (function)

Move block of memory (function)

Copy string (function)

Copy characters from string (function)

Concatenation - function
Description

Concatenate strings (function)

Append characters from string (function)

Comparison
Description

Compare two blocks of memory (function)

Compare two strings (function)

Compare two strings using locale (function)

Compare characters of two strings (function)

Transform string using locale (function)

Concatenation - function
Description

Concatenate strings (function)

Append characters from string (function)

Searching - function
Description

Locate character in block of memory (function)

Locate first occurrence of character in string (function)

Get span until character in string (function)

Locate characters in string (function)

Locate last occurrence of character in string (function)

Get span of character set in string (function)

Locate substring (function)

Split string into tokens (function)

Others - function
Description

Fill block of memory (function)

Get pointer to error message string (function)

Get string length (function)

Macros
Description

Null pointer (macro)

Types
Description

Unsigned integral type (type)

Reference

[1] https://www.runoob.com/cprogramming/c-standard-library-string-h.html

[2] https://cplusplus.com/reference/cstring/

最后更新于

这有帮助吗?