C++ String遍历

C++ 字符串数组有它自己的类,所以想独立出来处理。

如下面代码是string的遍历,已经根据空格来分离string的字符串。

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main(void)
{
	string s;
	string tmp;
	unsigned int i;
	cout << "Input strings and end with empty string:" <<endl;
	getline(cin, tmp);
	s = s + tmp;
	cout << "The strings is:" << s  << endl;
	tmp = ""; // empty tmp string
	for (i=0; i < s.size(); ++i){
		if (' ' == s[i]){
			cout << tmp << endl;
			tmp = "";
		} else {
			tmp = tmp + s[i];
			if (i == s.size() - 1)
				cout << tmp << endl;
		}	
	}
	return 0;
}



C++中,可以使用迭代器来遍历字符串。以下是一个示例代码,展示了如何使用迭代器遍历一个字符串并打印每个字符: ```c++ #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; for (std::string::iterator it = str.begin(); it != str.end(); ++it) { std::cout << *it << std::endl; } return 0; } ``` 在上面的代码中,我们首先创建了一个字符串对象 `str`,然后使用 `std::string::iterator` 类型定义了一个迭代器 `it`,并将其初始化为字符串的第一个字符的迭代器。在循环中,我们使用 `++it` 逐个遍历字符串中的字符,并使用 `*it` 获取当前字符的值。最后,我们将每个字符打印到控制台上。 除了使用迭代器遍历字符串之外,还可以使用C++标准库中的 `std::for_each` 函数和算法库中的 `std::string::const_iterator` 类型来遍历字符串。以下是一个使用 `std::for_each` 函数遍历字符串的示例代码: ```c++ #include <iostream> #include <algorithm> #include <string> int main() { std::string str = "Hello, world!"; std::for_each(str.begin(), str.end(), [](char c) { std::cout << c << std::endl; }); return 0; } ``` 在上面的代码中,我们使用 `std::for_each` 函数将一个 lambda 表达式作为第三个参数传递给函数,该表达式用于处理每个字符。这个 lambda 表达式使用 `char` 类型的参数 `c` 来获取当前字符的值,并打印到控制台上。这种方式也可以遍历字符串中的所有字符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值