21xrx.com
2025-07-07 15:12:01 Monday
文章检索 我的文章 写文章
C++如何输出文本中的'*'字符?
2023-07-05 05:33:50 深夜i     --     --
C++ 输出 文本 '*'字符

在使用C++进行文本处理时,我们常常需要对文本中的特定字符进行操作,而输出文本中的'*'字符也是一种常见需求。下面我们介绍几种实现方式。

方式一:使用for循环逐个输出字符

代码实现:

#include <iostream>
#include <string>
int main()
{
  std::string str = "hello world *********";
  for(const char& c : str)
  {
    if(c == '*')
    
      std::cout << c;
    
  }
  return 0;
}

方式二:使用字符串查找函数

代码实现:

#include <iostream>
#include <string>
int main()
{
  std::string str = "hello world *********";
  size_t pos = 0;
  while((pos = str.find('*', pos)) != std::string::npos)
  {
    std::cout << str[pos];
    pos++;
  }
  return 0;
}

方式三:使用正则表达式

代码实现:

#include <iostream>
#include <string>
#include <regex>
int main()
{
  std::string str = "hello world *********";
  std::regex reg("\\*");
  std::sregex_iterator it(str.begin(), str.end(), reg), end_it;
  for(; it != end_it; it++)
  {
    std::cout << (*it)[0];
  }
  return 0;
}

在以上三种方式中,使用for循环逐个输出字符的方式比较简单,但不够高效;使用字符串查找函数的方式虽然更高效,但对于一些复杂的匹配需求,正则表达式则是更好的选择。因此,我们可以根据具体需求灵活选择使用不同的方式来输出文本中的'*'字符。

  
  

评论区