21xrx.com
2025-03-18 12:33:39 Tuesday
文章检索 我的文章 写文章
C++字符串处理技巧分享
2023-07-10 00:47:50 深夜i     13     0
字符串 C++ 处理技巧 分享 编程

作为一种流行的编程语言,C++ 中的字符串处理技巧被广泛应用于各种应用程序和游戏开发中。下面,我们来分享一些 C++ 字符串处理的技巧,帮助您更好的掌握 C++ 中的字符串处理。

1. 字符串转换成整数

在 C++ 中,可以使用 `stoi` 函数将字符串转换成整数。该函数的使用方法如下所示:

#include <string>
#include <iostream>
int main()
{
  std::string str = "123";
  int num = std::stoi(str);
  std::cout << num << std::endl;
  return 0;
}

输出结果为:

123

2. 字符串追加操作

在 C++ 中,可以使用 `+=` 运算符将两个字符串进行追加操作。例如,如下示例代码:

#include <string>
#include <iostream>
int main()
{
  std::string str1 = "hello";
  std::string str2 = "world";
  str1 += str2;
  std::cout << str1 << std::endl;
  return 0;
}

输出结果为:

helloworld

3. 字符串查找操作

在 C++ 中,可以使用 `find` 函数来查找字符串中是否包含某个子字符串。该函数的使用方法如下所示:

#include <string>
#include <iostream>
int main()
{
  std::string str1 = "hello world";
  std::string str2 = "world";
  size_t pos = str1.find(str2);
  if (pos != std::string::npos)
  
    std::cout << "find " << str2 << " at position " << pos << std::endl;
  
  else
  
    std::cout << "not find " << str2 << std::endl;
  
  return 0;
}

输出结果为:

find world at position 6

4. 字符串分割操作

在 C++ 中,可以使用 `substr` 和 `find` 函数来进行字符串分割操作。例如,如下示例代码:

#include <string>
#include <iostream>
#include <vector>
int main()
{
  std::string str = "hello,world,!";
  std::vector<std::string> vec_str;
  size_t pos1 = 0;
  size_t pos2 = str.find(',');
  while (pos2 != std::string::npos)
  {
    vec_str.push_back(str.substr(pos1, pos2 - pos1));
    pos1 = pos2 + 1;
    pos2 = str.find(',', pos1);
  }
  vec_str.push_back(str.substr(pos1));
  for (auto it = vec_str.begin(); it != vec_str.end(); ++it)
  {
    std::cout << *it << std::endl;
  }
  return 0;
}

输出结果为:

hello
world
!

5. 字符串替换操作

在 C++ 中,可以使用 `replace` 函数来进行字符串替换操作。例如,如下示例代码:

#include <string>
#include <iostream>
int main()
{
  std::string str = "hello world";
  std::string old_str = "world";
  std::string new_str = "everyone";
  size_t pos = str.find(old_str);
  if (pos != std::string::npos)
  {
    str.replace(pos, old_str.length(), new_str);
  }
  std::cout << str << std::endl;
  return 0;
}

输出结果为:

hello everyone

这些 C++ 字符串处理技巧可以帮助您更加轻松和高效地完成字符串相关的编程任务。希望您喜欢这些技巧,愿您的 C++ 编程之路越来越顺畅!

  
  

评论区