Hello world travels in cpp - 字符串(2)

本文通过实例演示了如何使用C++进行字符串操作,包括查找特定字符的位置及按指定标记分割字符串的方法。首先介绍了如何判断字符在字符串中的位置,接着详细说明了如何利用循环和条件语句实现字符串的有效分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言

在上一篇的内容中我们通过helloworld,了解到了string的好处,那么在这里我们详细的来认识一下string的魅力吧。

w 藏在什么地方了

#include <iostream>
#include <string>

int main() {
  std::string str = "I am the hello world.";

  // 在开头吗?
  if (str[0] == 'w') { // or using: *(str.begin()) == 'w'
    std::cout << "在开头" << std::endl;
  } 
  else if (str[str.size()-1] == 'w') { // or using (*(str.end()-1) == 'w')
    std::cout << "在结尾" << std::endl;
  }
  else {
    for (std::string::iterator iter=str.begin(); iter!=str.end(); ++iter) {
      if (*iter == 'w') {
        std::cout << "找到了, 在第" << iter-str.begin() + 1 << std::endl;
      }
    }

    /* or using below c++11
    for (auto c : str) {
      if (c == 'w') {
        std::cout << "找到了, 在" << iter-str.begin() + 1 << std::endl;
      }
    }
    */
  }
}

在这里,有一点需要注意的是,代码所在文件的编码方式,打个比方说,windows系统内部支持的是gbk的编码方式,如果代码的编码方式是utf-8的话,这里输出的中文就是错误的样子,因此需要确保两者之间的编码方式是一致的。

分离hello world

现在,假如有一个字符串"hello world hello1 world1 hello2 world2",我们需要将这个整串字符串分离成不同的单词,该如何操作呢?

#include <iostream>
#include <string>
#include <vector>

using std::vector;
using std::string;
using std::cout;
using std::endl;

void seperate(const string &input, const char tag, vector<string> &output) {
  string tmp;
  for (auto c : input) {
    if (c != tag) {
      tmp = tmp + c;
    }
    else if (!tmp.empty()) {
      output.push_back(tmp);
      tmp.clear();
    }
  }

  // deal with the last word
  if (!tmp.empty()) {
    output.push_back(tmp);
  }
}

int main() {
  string str = "hello world hello1 world1 hello2 world2";
  vector<string> vec;

  seperate(str,' ',vec);

  for (auto v : vec) {
    cout << v << endl;
  }
}

转载于:https://my.oschina.net/grassyue/blog/167291

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值