1. 程式人生 > >設計一個字串類String(C++練習題)

設計一個字串類String(C++練習題)

要求:設計一個字串類String,可以求字串長度,可以連線兩個串(如,s1=“計算機”,s2=“軟體”,s1與s2連線得到“計算機軟體”),並且過載“=”運算子進行字串賦值,編寫主程式實現:s1="電腦科學",s2=“是發展最快的科學!”,求s1和s2的串長,連線s1和s2

 

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class String
{

    char str[255];

public:
    String(){str[
0]='\0';} String(char* s){strcpy_s(str,s);} String(String &s){strcpy_s(str,s.str);} String &operator=(String &); String &operator=(char*); void display(){cout<<str<<endl;} void strPlus(String); int strLen(){return strlen(str);} }; String& String::operator
=(String &s) { if(this==&s)return *this; strcpy_s(str,s.str); return *this; } String& String::operator =(char *s) { strcpy_s(str,s); return *this; } void String::strPlus(String s) { int i=strLen(); int j=s.strLen(); int k=0; while(k<=j) { str[i
++]=s.str[k++]; } } int _tmain() { String s1("計算機"); String s2("軟體"); s1.strPlus(s2); s1.display(); String s3="電腦科學"; String s4="是發展最快的科學!"; cout<<"求串長:電腦科學="<<s3.strLen()<<endl; cout<<"求串長:是發展最快的科學!="<<s4.strLen()<<endl; s3.strPlus(s4); s3.display(); getchar(); return 0; }