21xrx.com
2024-05-20 17:16:47 Monday
登录
文章检索 我的文章 写文章
C++中的String库函数有哪些?
2023-07-05 11:09:01 深夜i     --     --
C++ String 库函数 函数列表

C++是一种面向对象的编程语言,常用于开发跨平台应用程序、操作系统、嵌入式系统、3D图形和游戏等。在C++中,字符串操作是一项重要的功能,其中String库函数是最常用的函数之一。下面介绍一些常用的String库函数。

1. strlen()函数

strlen()函数是用于计算字符串的长度的函数。该函数接受一个字符串作为参数,并返回该字符串的长度。例如:


char str[] = "Hello, World!";

int len = strlen(str);

cout << "Length of str is " << len << endl;

输出为:“Length of str is 13”。

2. strcpy()函数

strcpy()函数是用于拷贝字符串的函数。它接受两个参数,第一个参数是目标字符串,第二个参数是源字符串。例如:


char dest[20];

char src[] = "Copy me!";

strcpy(dest, src);

cout << "Copied string is " << dest << endl;

输出为:“Copied string is Copy me!”。

3. strcat()函数

strcat()函数是用于连接两个字符串的函数。它接受两个参数,第一个参数是目标字符串,第二个参数是源字符串。例如:


char dest[20] = "Hello, ";

char src[] = "World!";

strcat(dest, src);

cout << "Concatenated string is " << dest << endl;

输出为:“Concatenated string is Hello, World!”。

4. strcmp()函数

strcmp()函数是用于比较两个字符串的函数。它接受两个参数,第一个参数是要比较的字符串A,第二个参数是要比较的字符串B。如果两个字符串相等,则返回0;如果字符串A大于字符串B,则返回大于0的整数;如果字符串A小于字符串B,则返回小于0的整数。例如:


char str1[] = "abc";

char str2[] = "def";

int result = strcmp(str1, str2);

if (result > 0)

  cout << "str1 is greater than str2" << endl;

else if (result < 0)

  cout << "str1 is less than str2" << endl;

else

  cout << "str1 and str2 are equal" << endl;

输出为:“str1 is less than str2”。

5. strstr()函数

strstr()函数是用于在一个字符串中查找指定字符串的函数。它接受两个参数,第一个参数是要查找的字符串,第二个参数是要查找的子字符串。如果找到了子字符串,则返回指向子字符串的指针;如果没有找到,则返回空指针。例如:


char str[] = "The quick brown fox jumps over the lazy dog";

char sub[] = "fox";

char *result = strstr(str, sub);

if (result != NULL)

  cout << "Sub string found at position " << result - str << endl;

else

  cout << "Sub string not found" << endl;

输出为:“Sub string found at position 16”。

以上是C++中一些常用的String库函数。它们能够满足大部分字符串操作需求,无论是字符串的长度、拷贝、连接、比较还是查找,都能够轻松实现。通过掌握这些函数,我们可以更加高效地处理字符串。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复