【C语言】常用字符串函数大盘点

【C语言】常用字符串函数大盘点

文章目录

  • 【C语言】常用字符串函数大盘点
    • 1. 字符串的基本概念
    • 2. 常用字符串函数
      • 2.1 字符串长度和复制
      • 2.2 字符串连接
      • 2.3 字符串比较
      • 2.4 字符串搜索
      • 2.5 字符串修改
      • 2.6字符串到数字的转换 - atoi, atol, strtol
      • 2.7数字到字符串的转换 - `itoa` (非标准,需要自定义实现)
    • 3. 使用字符串函数的注意事项

C语言提供了一组标准库函数,用于处理字符串,这些函数定义在 头文件中。这些函数可以帮助我们执行各种字符串操作,如复制、连接、比较、搜索和修改等。

1. 字符串的基本概念

在C语言中,字符串被视为字符数组,以空字符('\0')结尾。例如,字符串 “Hello” 实际上存储为 H e l l o \0

2. 常用字符串函数

2.1 字符串长度和复制

  • size_t strlen(const char *str);

    • 计算字符串str的长度,不包括结尾的空字符。
    • 返回值:字符串的长度。
    #include 
    #include 
    
    int main() {
        char str[] = "Hello, World!";
        printf("Length of string: %zu\n", strlen(str));
        return 0;
    }
    
  • char *strcpy(char *dest, const char *src);

    • src指向的字符串复制到dest指向的内存空间,包括空字符。
    • 返回值:指向dest的指针。
    #include 
    #include 
    
    int main() {
        char src[] = "Hello, World!";
        char dest[20];
        strcpy(dest, src);
        printf("Copied string: %s\n", dest);
        return 0;
    }
    
  • char *strncpy(char *dest, const char *src, size_t n);

    • src指向的字符串的前n个字符复制到dest指向的内存空间,包括空字符,如果src的长度小于n,则用空字符填充。
    • 返回值:指向dest的指针。
    #include 
    #include 
    
    int main() {
        char src[] = "Hello, World!";
        char dest[20];
        strncpy(dest, src, 5); // Copy only the first 5 characters
        dest[5] = '\0'; // Null-terminate the string
        printf("Copied string: %s\n", dest);
        return 0;
    }
    

2.2 字符串连接

  • char *strcat(char *dest, const char *src);

    • src指向的字符串连接到dest指向的字符串的末尾。
    • 返回值:指向dest的指针。
    #include 
    #include 
    
    int main() {
        char dest[] = "Hello, ";
        char src[] = "World!";
        strcat(dest, src);
        printf("Concatenated string: %s\n", dest);
        return 0;
    }
    
  • char *strncat(char *dest, const char *src, size_t n);

    • src指向的字符串的前n个字符连接到dest指向的字符串的末尾。
    • 返回值:指向dest的指针。
    #include 
    #include 
    
    int main() {
        char dest[30] = "Hello, ";
        char src[] = "World!";
        strncat(dest, src, 5); // Concatenate only the first 5 characters of src
        printf("Concatenated string: %s\n", dest);
        return 0;
    }
    

2.3 字符串比较

  • int strcmp(const char *str1, const char *str2);

    • 比较两个字符串str1str2
    • 返回值:如果str1小于str2返回负数,相等返回0,大于返回正数。
    #include 
    #include 
    
    int main() {
        char str1[] = "Apple";
        char str2[] = "Banana";
        int result = strcmp(str1, str2);
        if (result < 0) {
            printf("First string is less than second string.\n");
        } else {
            printf("First string is greater than or equal to second string.\n");
        }
        return 0;
    }
    
  • int strncmp(const char *str1, const char *str2, size_t n);

    • 比较两个字符串str1str2的前n个字符。
    • 返回值:如果str1小于str2返回负数,相等返回0,大于返回正数。
    #include 
    #include 
    
    int main() {
        char str1[] = "Apple";
        char str2[] = "Apricot";
        int result = strncmp(str1, str2, 2); // Compare only the first 2 characters
        if (result == 0) {
            printf("First part of both strings are equal.\n");
        } else {
            printf("First parts of strings are not equal.\n");
        }
        return 0;
    }
    

2.4 字符串搜索

  • char *strstr(const char *haystack, const char *needle);

    • haystack中搜索第一次出现的needle字符串。
    • 返回值:如果找到,返回指向第一次出现的needle的指针;否则返回NULL
    #include 
    #include 
    
    int main() {
        char haystack[] = "Hello, World!";
        char needle[] = "World";
        char *found = strstr(haystack, needle);
        if (found) {
            printf("Found substring: %s\n", found);
        } else {
            printf("Substring not found.\n");
        }
        return 0;
    }
    
  • char *strchr(const char *str, int c);

    • str中搜索第一次出现的字符c
    • 返回值:如果找到,返回指向第一次出现的c的指针;否则返回NULL
    #include 
    #include 
    
    int main() {
        char str[] = "Hello, World!";
        char *found = strchr(str, 'W');
        if (found) {
            printf("Found character at position: %ld\n", found - str + 1);
        } else {
            printf("Character not found.\n");
        }
        return 0;
    }
    

2.5 字符串修改

  • void *memset(void *s, int c, size_t n);

    • s指向的内存的前n个字节设置为0。
    • 返回值:指向s的指针。
    #include 
    #include 
    
    int main() {
        char buffer[10];
        memset(buffer, 0, 9); // Set the first 9 bytes to 0
        buffer[9] = '\0'; // Null-terminate the string
        printf("Buffer: %s\n", buffer);
        return 0;
    }
    
  • char *strrev(char *str);(非标准函数,需要自定义)

    • 反转字符串str
    • 返回值:指向反转后的字符串的指针。
    #include 
    #include 
    
    void strrev(char *str) {
        int len = strlen(str);
        for (int i = 0; i < len / 2; ++i) {
            char temp = str[i];
            str[i] = str[len - i - 1];
            str[len - i - 1] = temp;
        }
    }
    
    int main() {
        char str[] = "Hello, World!";
        strrev(str);
        printf("Reversed string: %s\n", str);
        return 0;
    }
    

2.6字符串到数字的转换 - atoi, atol, strtol

C语言提供了几个函数来实现这一功能,它们分别是atoiatolstrtol。这些函数可以将字符串转换为整数,但它们在处理的数值范围和错误检测方面有所不同。

  1. atoi - 字符串转换为int

atoi函数(ASCII to Integer)用于将字符串转换为int类型的整数。它的原型定义在头文件中。

原型:

int atoi(const char *str);

参数:

  • str:指向要转换的字符串的指针。

返回值:

  • 成功时返回转换后的整数值。
  • 如果转换失败(例如,字符串不是有效的整数表示),返回0。

示例代码:

#include 
#include 

int main() {
    char str[] = "12345";
    int value = atoi(str);
    printf("Integer value: %d\n", value);
    return 0;
}

2. atol - 字符串转换为long

atol函数(ASCII to Long)用于将字符串转换为long类型的整数。它的原型也定义在头文件中。

原型:

long atol(const char *str);

参数:

  • str:指向要转换的字符串的指针。

返回值:

  • 成功时返回转换后的长整数值。
  • 如果转换失败,返回0。

示例代码:

#include 
#include 

int main() {
    char str[] = "1234567890123456789";
    long value = atol(str);
    printf("Long value: %ld\n", value);
    return 0;
}

3. strtol - 字符串转换为long,带错误检测

strtol函数提供了更多的灵活性和错误检测功能。它的原型定义在头文件中。

原型:

long strtol(const char *str, char **endptr, int base);

参数:

  • str:指向要转换的字符串的指针。
  • endptr:如果非NULL,函数将在这里存储一个指针,指向str中第一个无法转换为数字的字符。
  • base:转换的基数,可以是2到36之间的任何整数,或者是0。如果base是0,函数会根据字符串的前缀自动确定基数(例如,"0x"表示十六进制)。

返回值:

  • 成功时返回转换后的长整数值。
  • 如果转换失败或字符串为空,返回0。
  • 如果溢出,返回LONG_MAXLONG_MIN

示例代码:

#include 
#include 

int main() {
    char str[] = "12345";
    char *endptr;
    long value = strtol(str, &endptr, 10); // Base 10
    if (endptr == str) {
        printf("No digits were found\n");
    } else {
        printf("Long value: %ld\n", value);
    }
    return 0;
}

2.7数字到字符串的转换 - itoa (非标准,需要自定义实现)

#include 
#include 

/* A simple implementation of itoa */
char* itoa(int value, char* str, int base) {
    char* ptr = str, *ptr1 = str, tmp_char;
    int tmp_value;

    do {
        tmp_value = value;
        value /= base;
        *ptr++ = "0123456789abcdef"[(unsigned) (tmp_value - value * base)];
    } while (value);

    *ptr-- = '\0';
    while (ptr1 < ptr) {
        tmp_char = *ptr;
        *ptr-- = *ptr1;
        *ptr1++ = tmp_char;
    }
    return str;
}

int main() {
    int num = 255;
    char buffer[50];
    itoa(num, buffer, 10);
    printf("String representation: %s\n", buffer);
    return 0;
}

3. 使用字符串函数的注意事项

  1. 内存安全:在使用字符串函数时,确保目标字符串有足够的空间来存储结果,以避免缓冲区溢出。
  2. 空字符:C语言中的字符串以空字符结尾,确保在使用字符串函数时考虑到这一点。
  3. 返回值:许多字符串函数返回指向字符串的指针,这些返回值可以用来进一步操作字符串。

通过掌握这些基本的字符串函数,你可以在C语言中有效地处理字符串,编写更加健壮和安全的程序。

你可能感兴趣的:(C语言,c语言,算法,开发语言)