VC++中的string 用法

来源:互联网 发布:微信开发框架java 编辑:程序博客网 时间:2024/06/06 03:22

CString是MFC的,它是C++特有的一种形式,并不是类

string用法总结如下:

1.string是一个类,而不是一个系统变量类型;

2.使用时可以看成为字符串变量类型;

3.使用时必须包含string.h文件,但.h不能够出现,即#include <string> 

4.必须声明使用名空间,即using namespacestd;

iostream.h是98年C++标准出来之前的库,现在都是为与遗留代码保持兼容而提供的(在vc2003和vc2005中已没有iostream.h)。
引入c++标准之后,标准C++的库都处于::std名字空间之内,而老的库是直接把东西放在全局名字空间::内的。
还有,iostream.h 的流库以前不是模板,而标准库中的都是模板.
vc中string和string.h是不一样的string是c++提供的string类的头文件,而string.h则包含了C语言中的字符串操作函数的文件,如strcpy,memset等.

程序一:

#include <iostream>  
#include <string>        // 为用string这个必须
using namespace std; // 为用string这个必须
int main()
{
cout<<"what's your name ?\n";
string name;
cin>>name;
cout<<"the user'name is:"<<name;
return 0;
}

程序二(http://blog.sina.com.cn/s/blog_5396775a0100fxu7.html):

#include <string>    //  使用 string 类时须包含这个文件
#include <iostream>

using namespace std;

int main()
{
    string str1;
  
    //  输入与输出
    cout << "输入字符串 str1" << endl;
    cin >> str1; getchar();
    cout << str1 << endl << endl << endl;
   
    //  一行行读取
    cout << "输入字符串 str1" << endl;
    getline( cin, str1 );
    cout << str1 << endl;

    //   c字符转换
    string str2("Hello World!"), str3;
    char   str4[50];

    cout << "输入 C 字符串" << endl;
    scanf("%s",str4);
    str3= str4;

    cout << "str2 is " << str2 << endl;
    cout << "str3 is " << str3 << endl << endl << endl;

    //  求字符串的长度
    string str5;
    cout << "输入字符串 str5" << endl;
    cin >> str5;
    int   len= str5.size();
    cout << "字符串 str5的长度为" << len << endl << endl << endl;

    //  遍历字符串例子
    string str6;
    cout << "输入字符串 str6" << endl;
    cin >> str6;
    int i;
    for( i= 0; i< str6.size(); ++i )
    cout << str6[i];
    cout << endl << endl;

    //  比较两个字符串   比较规则同 c字符串比较规则
    string str7, str8;
    cout << "输入字符串 str7, str8 , 中间用空格格开" << endl;
    cin >> str7 >> str8;

    if( str7< str8 ) cout << str7 << "  小于 " << str8 << endl;
    else if( str7> str8 ) cout << str7 << "  大于 " << str8 << endl;
    else cout << str7 << "  等于 " << str8 << endl;
   
   
    //  字符串与字符相加
    string str9= "Darren";
    char ch1= 'a', ch2= 'b';
    str9= str9+ ch1; cout << str9 << endl << endl;
    str9= ch2+ str9; cout << str9 << endl << endl << endl;
   
    //  字符串与字符串相加
    string str10= "Acm", str11= "ICPC";
    str10.append( str11 );
    cout << str10 << endl << endl;
   
    //  字符串是否包含子串  如果包含则返回子串在目标串中第一次出现的位置
    string str12= "I am a student", str13= "student", str14= "aaaaaaa";
    if( str12.find( str13 )!= -1 )  cout << "Find " << str13 << endl;
    if( str12.find( str14 )== -1 )  cout << "Not Find  " << str14 << endl;
   
    //  转换成 c_字符串
    string str15= "Hello World";
    printf("%s\n", str15.c_str() );
    
    system("pause");

    return 0;
}