字符串的应用实例
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
string food;
int count=0;
cout << "你最喜欢吃什么?" << endl;
while (cin >> food)//输入完毕ctrl+z结束
{
count = count + 1;
cout << "你最喜欢吃的第" << count << "种美食是: " << food << endl;
cout << "你还喜欢吃什么?" << endl;
}
cout << "你最喜欢吃的食物有" << count << "种" << endl;
system("pause");
return 0;
}
#include<iostream>
#include<Windows.h>
#include <string>
using namespace std;
int main()
{
string address;
cout << "帅哥,暑假打算去哪里旅游啊?" << endl;
getline(cin, address);
if (address.empty())
{
cout << "输入数据为空" << endl;
}
else
{
cout << "太巧了,我也打算去" << address << endl;
}
cout << "地址的长度是" << address.size() << endl;
cout << "地址的长度是" << address.length() << endl;
system("pause");
return 0;
}
字符串的比较
小例子
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
string myGirl = "小张";
string yourGirl;
cout << "你喜欢的女孩叫什么名字?" << endl;
cin >> yourGirl;
if (yourGirl == myGirl)
{
cout << "我们喜欢同一人,来决斗吧!!!!!!" << endl;
}
else
{
cout << "祝你幸福" << endl;
}
system("pause");
return 0;
}
字符串的加法
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
string s1 = "a";
string s2 = "b";
string s3 = "c";
string s4 = "d";
string s5;
s5 = s1 + s2 + s3 + s4;
cout << s5<<endl;
s5 += "666";//s5变为abcd+666
cout << s5<<endl;
system("pause");
return 0;
}
补充:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<Windows.h>
#include<stdio.h>
using namespace std;
int main()
{
char name[32];
printf("请输入您的名字: ");
scanf("%s", name);
printf("您的名字为: %s\n",name);
system("pause");
return 0;
}