唐峰0

primer_C++_3.2 标准库类型string

 

 

/*
*输出string对象的第一个字符
*/

#include <iostream>
#include <string>

using namespace std;
int main()
{
	string str("Hello World!!!");
	if(!str.empty())
	cout << str[0] << endl;

	return 0;
}

  将字符串首字符改成大写:

#include <iostream>
#include <string>

using namespace std;
int main()
{
	string str("hello world!!!");
	if (!str.empty())
		str[0] = toupper(str[0]);

	cout << str<< endl;

	return 0;
}

  使用下标执行迭代:把str的第一个词改成大写形式:

#include <iostream>
#include <string>

using namespace std;
int main()
{
	string str("hello world!!!");
	for (decltype (str.size()) index = 0; index != str.size() && !isspace(str[index]); ++index)
		str[index] = toupper(str[index]);

	cout << str << endl;

	return 0;
}

  

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
	const string hexdigits = "0123456789ABCDEF";
	cout << "Enter a series of numbers between 0 and 15 "
		<< " separated by spaces. Hit ENTER when finished: "
		<< endl;
	string result;				//保存十六进制的字符串
	string::size_type n;		//保存从输入流读取的数
	while (cin >> n)
		if (n < hexdigits.size())	//忽略无效输入
			result += hexdigits[n];	//得到对应的十六进制数字
	cout << "Your hex number is: " << result << endl;
	return 0;
}

  3.2.3 

// 3.2.3_for使用 
//

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str= "Hello World";
	for (auto& c : str)
		c = 'X' ;
	cout << str << endl;
	return 0;
}

  

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str= "Hello World";
	for (char &c : str)
		c = 'X' ;
	cout << str << endl;
	return 0;
}

  

 

/*
* 读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分
*/

#include <iostream>
#include <string>
using namespace std;

int main()
{
	cout<<"请输入一段字符串:"<<endl;

	string str;
	cin >> str;
	
	for (auto& c : str)
	
		if (!ispunct(c))
			cout << c;

	return 0;
}

      

 

posted on 2019-07-17 09:16  唐峰0  阅读(209)  评论(0编辑  收藏  举报

导航