码迷,mamicode.com
首页 > 编程语言 > 详细

设计一个字符串类String(C++练习题)

时间:2018-12-01 18:32:08      阅读:857      评论:0      收藏:0      [点我收藏+]

标签:ios   play   etc   ring   tor   public   get   space   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;
}

 

设计一个字符串类String(C++练习题)

标签:ios   play   etc   ring   tor   public   get   space   c++   

原文地址:https://www.cnblogs.com/junjunjun123/p/10049344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!