Bootstrap

C++实现输出简单的字符串程序

本段代码引用《算法之美》这本书,主要为了记录学习的过程,因为有些代码挺好的,所以想在博客分享一下

代码如下

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

int main(int argc, char** argv)
{
	string str = "高德纳 美国 计算机科学家 计算机程序设计艺术";
	string str_temp = "";
	str_temp.assign(str);

	string result[4] = { "", "", "", ""};

	int position = 0;

	for (int i = 0; i < 3; i++)
	{
		position = str_temp.find(" ");
		result[i] = str_temp.substr(0, position);
		str_temp = str_temp.substr(position + 1, str_temp.length() - position);
	}
	result[3] = str_temp;

	cout << "姓名:" << setw(8) << result[0] << endl;
	cout << "国籍:" << setw(6) << result[1] << endl;
	cout << "职业:" << setw(14) << result[2] << endl;
	cout << "代表作:" << setw(18) << result[3] << endl;

	str_temp.swap(result[0]);
	

	for (int j = 1; j < 4; j++)
	{
		str_temp += " ";
		str_temp.append(result[j]);
	}

	int equal = str.compare(str_temp);

	if (equal == 0)
	{
		cout << "Successful Matching! " << endl;
	}
	else
		cout << "Unsuccessful Matching! " << endl;
 	return 0;
}

代码实现效果如下

 

;