MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

C++ 字符串函数大全

2024-01-054.8k 阅读

C++ 字符串函数概述

在C++ 编程中,字符串处理是一项极为常见且重要的任务。C++ 提供了丰富的字符串函数,这些函数主要分为两类:一类是基于C风格字符串(以'\0'结尾的字符数组)的函数,定义在<cstring>头文件中;另一类是基于C++ 标准库std::string类的成员函数和非成员函数,定义在<string>头文件中。

C风格字符串函数

strlen

strlen函数用于计算C风格字符串的长度,不包括字符串结束符'\0'。其函数原型为:

size_t strlen(const char* str);

示例代码如下:

#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, World!";
    size_t length = strlen(str);
    std::cout << "The length of the string is: " << length << std::endl;
    return 0;
}

在上述代码中,通过strlen函数获取了字符串"Hello, World!"的长度,并输出结果。strlen函数通过遍历字符串,直到遇到'\0'来确定字符串的长度。

strcpy

strcpy函数用于将一个C风格字符串复制到另一个字符数组中。其函数原型为:

char* strcpy(char* destination, const char* source);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    char source[] = "Hello";
    char destination[20];
    strcpy(destination, source);
    std::cout << "Copied string: " << destination << std::endl;
    return 0;
}

需要注意的是,使用strcpy时,目标数组必须足够大,以容纳源字符串及其结束符'\0',否则会导致缓冲区溢出错误。

strncpy

strncpy函数是strcpy的安全版本,它最多复制指定数量的字符。其函数原型为:

char* strncpy(char* destination, const char* source, size_t num);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    char source[] = "Hello, World!";
    char destination[6];
    strncpy(destination, source, 5);
    destination[5] = '\0'; // 手动添加结束符
    std::cout << "Copied string: " << destination << std::endl;
    return 0;
}

在这个例子中,strncpy最多复制5个字符到destination数组中。由于没有自动添加结束符,所以需要手动添加'\0'

strcat

strcat函数用于将一个C风格字符串追加到另一个字符串的末尾。其函数原型为:

char* strcat(char* destination, const char* source);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    char destination[20] = "Hello";
    char source[] = ", World!";
    strcat(destination, source);
    std::cout << "Concatenated string: " << destination << std::endl;
    return 0;
}

同样,使用strcat时要确保目标数组有足够的空间容纳追加后的字符串。

strncat

strncat函数是strcat的安全版本,它最多追加指定数量的字符。其函数原型为:

char* strncat(char* destination, const char* source, size_t num);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    char destination[20] = "Hello";
    char source[] = ", World!";
    strncat(destination, source, 3);
    std::cout << "Concatenated string: " << destination << std::endl;
    return 0;
}

这里最多追加3个字符到destination字符串末尾。

strcmp

strcmp函数用于比较两个C风格字符串。如果两个字符串相等,返回0;如果第一个字符串小于第二个字符串,返回一个负整数;如果第一个字符串大于第二个字符串,返回一个正整数。其函数原型为:

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

示例代码:

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "apple";
    const char* str2 = "banana";
    int result = strcmp(str1, str2);
    if (result < 0) {
        std::cout << str1 << " is less than " << str2 << std::endl;
    } else if (result > 0) {
        std::cout << str1 << " is greater than " << str2 << std::endl;
    } else {
        std::cout << str1 << " is equal to " << str2 << std::endl;
    }
    return 0;
}

字符串比较是基于字典序,逐个字符进行比较。

strncmp

strncmp函数与strcmp类似,但它最多比较指定数量的字符。其函数原型为:

int strncmp(const char* str1, const char* str2, size_t num);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "apple";
    const char* str2 = "applet";
    int result = strncmp(str1, str2, 4);
    if (result < 0) {
        std::cout << str1 << " is less than " << str2 << " in the first 4 characters" << std::endl;
    } else if (result > 0) {
        std::cout << str1 << " is greater than " << str2 << " in the first 4 characters" << std::endl;
    } else {
        std::cout << str1 << " is equal to " << str2 << " in the first 4 characters" << std::endl;
    }
    return 0;
}

在这个例子中,只比较了前4个字符。

strchr

strchr函数用于在C风格字符串中查找指定字符的首次出现位置。其函数原型为:

char* strchr(const char* str, int character);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, World!";
    char* result = strchr(str, 'o');
    if (result != nullptr) {
        std::cout << "The character 'o' found at position: " << result - str << std::endl;
    } else {
        std::cout << "The character 'o' was not found." << std::endl;
    }
    return 0;
}

strchr返回一个指向字符首次出现位置的指针,如果未找到则返回nullptr。通过指针相减可以得到字符的位置。

strrchr

strrchr函数与strchr类似,但它查找指定字符在字符串中最后一次出现的位置。其函数原型为:

char* strrchr(const char* str, int character);

示例代码:

#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, World!";
    char* result = strrchr(str, 'o');
    if (result != nullptr) {
        std::cout << "The last 'o' found at position: " << result - str << std::endl;
    } else {
        std::cout << "The character 'o' was not found." << std::endl;
    }
    return 0;
}

这里查找的是字符'o'最后一次出现的位置。

strstr

strstr函数用于在一个C风格字符串中查找另一个字符串的首次出现位置。其函数原型为:

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

示例代码:

#include <iostream>
#include <cstring>

int main() {
    const char* haystack = "Hello, World!";
    const char* needle = "World";
    char* result = strstr(haystack, needle);
    if (result != nullptr) {
        std::cout << "The substring '" << needle << "' found at position: " << result - haystack << std::endl;
    } else {
        std::cout << "The substring '" << needle << "' was not found." << std::endl;
    }
    return 0;
}

strstr返回一个指向子字符串首次出现位置的指针,如果未找到则返回nullptr

C++ std::string类函数

构造函数

std::string类有多个构造函数,常见的有:

std::string(); // 默认构造函数,创建一个空字符串
std::string(const char* s); // 使用C风格字符串构造
std::string(const std::string& other); // 拷贝构造函数
std::string(size_t n, char c); // 创建包含n个字符c的字符串

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s1;
    std::string s2 = "Hello";
    std::string s3(s2);
    std::string s4(5, 'a');
    std::cout << "s1: " << s1 << std::endl;
    std::cout << "s2: " << s2 << std::endl;
    std::cout << "s3: " << s3 << std::endl;
    std::cout << "s4: " << s4 << std::endl;
    return 0;
}

这里展示了不同构造函数的使用。

length和size

lengthsize函数都用于获取std::string的长度,它们的功能完全相同。其函数原型为:

size_t length() const;
size_t size() const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::cout << "Length of the string: " << s.length() << std::endl;
    std::cout << "Size of the string: " << s.size() << std::endl;
    return 0;
}

输出结果表明lengthsize返回相同的值。

empty

empty函数用于检查std::string是否为空。其函数原型为:

bool empty() const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "";
    std::string s2 = "Hello";
    std::cout << "s1 is empty: " << (s1.empty()? "Yes" : "No") << std::endl;
    std::cout << "s2 is empty: " << (s2.empty()? "Yes" : "No") << std::endl;
    return 0;
}

根据字符串是否为空返回相应的布尔值。

clear

clear函数用于清空std::string,将其长度设置为0。其函数原型为:

void clear();

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello";
    std::cout << "Before clear: " << s << ", length: " << s.length() << std::endl;
    s.clear();
    std::cout << "After clear: " << s << ", length: " << s.length() << std::endl;
    return 0;
}

执行clear后,字符串变为空字符串,长度为0。

append

append函数用于在std::string末尾追加内容。它有多种重载形式,例如:

std::string& append(const std::string& str);
std::string& append(const char* s);
std::string& append(size_t n, char c);

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "Hello";
    std::string s2 = ", World!";
    s1.append(s2);
    std::cout << "Appended string: " << s1 << std::endl;

    s1.append(" Again");
    std::cout << "Appended again: " << s1 << std::endl;

    s1.append(3, '!');
    std::cout << "Appended characters: " << s1 << std::endl;
    return 0;
}

通过不同的重载形式,可以追加字符串、C风格字符串或多个相同字符。

operator+=

operator+=append的简洁写法,用于在std::string末尾追加内容。例如:

std::string s1 = "Hello";
std::string s2 = ", World!";
s1 += s2;

这与使用append函数的效果相同。

assign

assign函数用于替换std::string的内容。它也有多种重载形式,如:

std::string& assign(const std::string& str);
std::string& assign(const char* s);
std::string& assign(size_t n, char c);

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "Hello";
    s1.assign("Goodbye");
    std::cout << "Assigned string: " << s1 << std::endl;

    s1.assign(5, 'a');
    std::cout << "Assigned characters: " << s1 << std::endl;
    return 0;
}

通过assign可以用新的内容替换原字符串。

substr

substr函数用于获取std::string的子字符串。其函数原型为:

std::string substr(size_t pos = 0, size_t len = npos) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string sub1 = s.substr(0, 5);
    std::string sub2 = s.substr(7);
    std::cout << "Substring 1: " << sub1 << std::endl;
    std::cout << "Substring 2: " << sub2 << std::endl;
    return 0;
}

这里substr(0, 5)获取从位置0开始长度为5的子字符串,substr(7)获取从位置7开始到字符串末尾的子字符串。

find

find函数用于在std::string中查找子字符串或字符。它有多种重载形式,例如:

size_t find(const std::string& str, size_t pos = 0) const;
size_t find(char c, size_t pos = 0) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    size_t pos1 = s.find("World");
    size_t pos2 = s.find('o');
    if (pos1 != std::string::npos) {
        std::cout << "Substring 'World' found at position: " << pos1 << std::endl;
    }
    if (pos2 != std::string::npos) {
        std::cout << "Character 'o' found at position: " << pos2 << std::endl;
    }
    return 0;
}

如果找到则返回位置,否则返回std::string::npos

rfind

rfind函数与find类似,但它查找子字符串或字符最后一次出现的位置。其函数原型为:

size_t rfind(const std::string& str, size_t pos = npos) const;
size_t rfind(char c, size_t pos = npos) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    size_t pos1 = s.rfind("o");
    if (pos1 != std::string::npos) {
        std::cout << "Last 'o' found at position: " << pos1 << std::endl;
    }
    return 0;
}

这里查找字符'o'最后一次出现的位置。

find_first_of

find_first_of函数用于查找std::string中第一个与指定字符串中的任意字符匹配的字符位置。其函数原型为:

size_t find_first_of(const std::string& str, size_t pos = 0) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string search = "aeiou";
    size_t pos = s.find_first_of(search);
    if (pos != std::string::npos) {
        std::cout << "First vowel found at position: " << pos << std::endl;
    }
    return 0;
}

这里查找字符串s中第一个元音字母的位置。

find_last_of

find_last_of函数与find_first_of类似,但它查找最后一个与指定字符串中的任意字符匹配的字符位置。其函数原型为:

size_t find_last_of(const std::string& str, size_t pos = npos) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string search = "aeiou";
    size_t pos = s.find_last_of(search);
    if (pos != std::string::npos) {
        std::cout << "Last vowel found at position: " << pos << std::endl;
    }
    return 0;
}

这里查找字符串s中最后一个元音字母的位置。

find_first_not_of

find_first_not_of函数用于查找std::string中第一个不与指定字符串中的任意字符匹配的字符位置。其函数原型为:

size_t find_first_not_of(const std::string& str, size_t pos = 0) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string search = "aeiou";
    size_t pos = s.find_first_not_of(search);
    if (pos != std::string::npos) {
        std::cout << "First non - vowel found at position: " << pos << std::endl;
    }
    return 0;
}

这里查找字符串s中第一个非元音字母的位置。

find_last_not_of

find_last_not_of函数与find_first_not_of类似,但它查找最后一个不与指定字符串中的任意字符匹配的字符位置。其函数原型为:

size_t find_last_not_of(const std::string& str, size_t pos = npos) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string search = "aeiou";
    size_t pos = s.find_last_not_of(search);
    if (pos != std::string::npos) {
        std::cout << "Last non - vowel found at position: " << pos << std::endl;
    }
    return 0;
}

这里查找字符串s中最后一个非元音字母的位置。

replace

replace函数用于替换std::string中的子字符串。它有多种重载形式,例如:

std::string& replace(size_t pos, size_t len, const std::string& str);
std::string& replace(const_iterator i1, const_iterator i2, const std::string& str);

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    s.replace(0, 5, "Goodbye");
    std::cout << "Replaced string: " << s << std::endl;

    std::string s2 = "Hello, World!";
    auto it1 = s2.begin();
    auto it2 = s2.begin() + 5;
    s2.replace(it1, it2, "Goodbye");
    std::cout << "Replaced by iterators: " << s2 << std::endl;
    return 0;
}

通过不同的重载形式,可以根据位置和长度或迭代器范围来替换子字符串。

insert

insert函数用于在std::string中插入内容。它也有多种重载形式,如:

std::string& insert(size_t pos, const std::string& str);
std::string& insert(const_iterator p, size_t n, char c);

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello!";
    s.insert(5, ", World");
    std::cout << "Inserted string: " << s << std::endl;

    std::string s2 = "Hello!";
    auto it = s2.begin() + 5;
    s2.insert(it, 3, '!');
    std::cout << "Inserted characters: " << s2 << std::endl;
    return 0;
}

可以在指定位置插入字符串或多个相同字符。

erase

erase函数用于删除std::string中的字符。其函数原型为:

std::string& erase(size_t pos = 0, size_t len = npos);
std::string& erase(const_iterator p);
std::string& erase(const_iterator first, const_iterator last);

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    s.erase(0, 5);
    std::cout << "Erased by position and length: " << s << std::endl;

    std::string s2 = "Hello, World!";
    auto it = s2.begin() + 7;
    s2.erase(it);
    std::cout << "Erased by iterator: " << s2 << std::endl;

    std::string s3 = "Hello, World!";
    auto it1 = s3.begin() + 7;
    auto it2 = s3.begin() + 12;
    s3.erase(it1, it2);
    std::cout << "Erased by iterator range: " << s3 << std::endl;
    return 0;
}

通过不同的重载形式,可以根据位置和长度、单个迭代器或迭代器范围来删除字符。

compare

compare函数用于比较两个std::string。它与C风格字符串的strcmp类似,返回值含义相同。其函数原型为:

int compare(const std::string& str) const;

示例代码:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "apple";
    std::string s2 = "banana";
    int result = s1.compare(s2);
    if (result < 0) {
        std::cout << s1 << " is less than " << s2 << std::endl;
    } else if (result > 0) {
        std::cout << s1 << " is greater than " << s2 << std::endl;
    } else {
        std::cout << s1 << " is equal to " << s2 << std::endl;
    }
    return 0;
}

根据比较结果输出相应信息。

c_str

c_str函数用于将std::string转换为C风格字符串(以'\0'结尾的字符数组)。其函数原型为:

const char* c_str() const;

示例代码:

#include <iostream>
#include <string>
#include <cstring>

int main() {
    std::string s = "Hello";
    const char* cstr = s.c_str();
    size_t length = strlen(cstr);
    std::cout << "C - style string length: " << length << std::endl;
    return 0;
}

这里将std::string转换为C风格字符串,并使用strlen获取其长度。

通过掌握这些C++ 字符串函数,开发者能够更加高效、灵活地处理字符串相关的任务,无论是简单的字符串拼接、查找,还是复杂的文本处理。在实际编程中,应根据具体需求选择合适的字符串函数,同时要注意函数的使用细节,如缓冲区溢出等问题,以确保程序的正确性和稳定性。