📄 string2.cpp
字号:
// string2.cpp -- String class methods
#include <cstring> // string.h for some
#include "String2.h" // include <iostream>
using std::cin;
using std::cout;
const int String::CINLIM = 80;
String::String()
{
len = 0;
str = new char[1];
str[0] = '\0'; // default string
}
// class methods
String::String(const char * s) // construct String from C string
{
len = strlen(s); // set size
str = new char[len+1]; // allot storage
strcpy(str,s);
}
String::String(const String & st) // copy constructor
{
len = st.len;
str = new char[len+1];
strcpy(str,st.str);
}
String::~String() // necessary destructor
{
delete[]str;
}
void String::stringlow() // tolower
{
char * str_temp = str;
while(*str_temp)
{
*str_temp = tolower(*str_temp);
str_temp++;
}
}
void String::stringup() // toupper
{
char * str_temp = str;
while(*str_temp)
{
*str_temp = toupper(*str_temp);
str_temp++;
}
}
int String::has(const char & c)const // count how many 'c' in string
{
int n = 0;
char * str_temp = str;
while(*str_temp)
{
if(c == *str_temp)
n++;
str_temp++;
}
return n;
}
// overloaded operator methods
// assign a String to a String
String & String::operator= (const String & st)
{
if (this == &st)
return *this;
delete []str;
len = st.len;
str = new char[len+1];
strcpy (str, st.str);
return *this;
}
String & String::operator = (const char * s)
{
delete []str;
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
return *this;
}
// read-write char access for non-const String
char & String::operator [] (int i)
{
return str[i];
}
// read-only char access for const String
const char & String::operator [] (int i)const
{
return str[i];
}
String String::operator + (const String & st)
{
String temp;
temp.len = len + st.len;
delete []temp.str;
temp.str = new char[temp.len+1];
strcat(temp.str,str);
strcat(temp.str,st.str);
return temp;
}
String String::operator + (const char * st)
{
String temp;
temp.len = len + strlen(st);
delete []temp.str;
temp.str = new char[temp.len+1];
strcat(temp.str,str);
strcat(temp.str,st);
return temp;
}
// overload operator friends
bool operator< (const String &st1, const String &st2)
{
return ( strcmp(st1.str,st2.str) < 0 );
}
bool operator> (const String &st1, const String &st2)
{
return st2.str < st1.str;
}
bool operator == (const String &st1, const String &st2)
{
return (strcmp(st1.str,st2.str) == 0);
}
// simple String output
ostream & operator<< (ostream & os, const String &st)
{
os<<st.str;
return os;
}
// quick and dirty String input
istream & operator>> (istream & is, String & st)
{
char temp[String::CINLIM];
if (is)
st = temp;
while (is && is.get() != '\n') // 超过CINLIM则从输入流中去除
continue;
return is;
}
String operator + (const char * st1, const String & st2) // 主要是重载 + 操作符不明白
{
String temp;
temp.len = strlen(st1) + st2.len;
delete []temp.str;
temp.str = new char[temp.len+1];
strcat(temp.str,st1);
strcat(temp.str,st2.str);
return temp;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -