21xrx.com
2024-09-20 01:09:03 Friday
登录
文章检索 我的文章 写文章
C++字符串操作技巧
2023-07-05 13:00:59 深夜i     --     --
C++ 字符串 操作 技巧 函数

C++作为一种广泛使用的编程语言,其字符串操作技巧也是非常重要的一部分。在编写程序时,我们经常需要对字符串进行各种操作,例如拼接、修改、查找等等。下面就来介绍一些C++字符串操作的技巧。

1.字符串长度的获取

在C++中,我们可以使用`strlen()`函数来获取一个字符串的长度。例子如下:


char str[] = "hello world";

int len1 = strlen(str);   // 获取字符串长度

cout << len1 << endl;    // 输出:11

此外,C++标准库中的`string`类还提供了`size()`函数来获取字符串长度,使用方法如下:


string str = "hello world";

int len2 = str.size();    // 获取字符串长度

cout << len2 << endl;    // 输出:11

2.字符串比较

在C++中,我们可以使用`strcmp()`函数来比较两个字符串的大小,例子如下:


char str1[] = "hello";

char str2[] = "world";

int res = strcmp(str1, str2);   // 比较字符串

cout << res << endl;       // 输出:-15

如果两个字符串相等,`strcmp()`函数会返回0。如果第一个字符串小于第二个字符串,`strcmp()`函数会返回一个负数,反之则返回一个正数。

3.字符串拼接

在C++中,我们可以使用`strcat()`函数来将一个字符串拼接到另一个字符串的后面,例子如下:


char str1[] = "hello";

char str2[] = "world";

strcat(str1, str2);     // 拼接字符串

cout << str1 << endl;    // 输出:hello world

需要注意的是,使用`strcat()`函数时,被拼接的字符串必须具有足够的空间来容纳拼接后的结果。

4.字符串查找

在C++中,我们可以使用`strstr()`函数来查找一个字符串在另一个字符串中出现的位置,例子如下:


char str1[] = "hello";

char str2[] = "llo";

char* res = strstr(str1, str2);  // 查找字符串

if (res != NULL)

  cout << "找到匹配的位置:" << res - str1 << endl; // 输出:找到匹配的位置:2

else

  cout << "未找到匹配的位置!" << endl;

需要注意的是,在使用`strstr()`函数时,如果查找到了指定的字符串,函数会返回指向该字符串在原字符串中的指针;如果未查找到,则会返回一个空指针。

以上就是关于C++字符串操作的一些技巧介绍,希望对大家有所帮助!

  
  

评论区

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