字符串类的常用函数

成员函数 功能描述
operator[](i) 操作符重载函数,访问指定下标的字符
startWith(s) 判断字符串是否以 s 开头
endOf(s) 判断字符串是否以 s 结尾
insert(i,s) 在字符串的位置 i 插入 s
trim() 去掉字符串两端的空白

重载数组访问操作符[]

  • char &operator [] (int i);
  • char operator [] (int i) const;

    • 注意事项

      • 当 i 的取值不合法时,抛出异常

        • 合法范围: (0 <= i) && (i < m_length)

判断是否以指定字符串开始或结束

  • bool startWith(const char *s) const;
  • bool startWith(const String &s) const;
  • bool endOf(const char *s) const;
  • bool endOf(const String &s) const;

image.png

image.png

在指定位置插入字符串

  • String &insert(int i, const char *s);
  • String &insert(int i, const String &s);

image.png

去掉字符串两端的空白字符

  • String &trim();

image.png

编程实验:常用成员函数的实现

文件:DTString.h

#ifndef STRING_H
#define STRING_H

#include "Exception.h"
#include "Object.h"

#include <cstdint>

namespace DTLib
{

class String
{
public:
    String();
    String(const String &s);
    String(const char* s);

    size_t length() const;
    const char *str() const;

    bool startWith(const char *s) const;
    bool startWith(const String &s) const;
    bool endOf(const char *s) const;
    bool endOf(const String &s) const;

    String &insert(size_t i, const char *s);
    String &insert(size_t i, const String &s);

    String &trim();

    bool operator == (const char *s) const;
    bool operator == (const String &s) const;
    bool operator != (const char *s) const;
    bool operator != (const String &s) const;
    bool operator > (const char *s) const;
    bool operator > (const String &s) const;
    bool operator < (const char *s) const;
    bool operator < (const String &s) const;
    bool operator >= (const char *s) const;
    bool operator >= (const String &s) const;
    bool operator <= (const char *s) const;
    bool operator <= (const String &s) const;

    String operator + (const char *s) const;
    String operator + (const String &s) const;
    String &operator += (const char *s);
    String &operator += (const String &s);

    String &operator = (const char c);
    String &operator = (const char *s);
    String &operator = (const String &s);

    char &operator[] (size_t i);
    char operator[] (size_t i) const;

    ~String();

protected:
    char *m_str = nullptr;
    size_t m_length = 0;
};

}

#endif // STRING_H

文件:DTString.cpp

#include "DTString.h"

#include <cstring>
#include <cstdlib>

namespace DTLib
{

String::String() : String("")
{
}

String::String(const String &s) : String(s.m_str)
{
}

String::String(const char* s)
{
    char* str = strdup(s);

    if (str != nullptr)
    {
        m_str = str;

        m_length = strlen(str);
    }
    else
    {
        THROW_EXCEPTION(NoEnoughMemoryException, "No enogh memory to create str object ...");
    }
}

size_t String::length() const
{
    return m_length;
}

const char *String::str() const
{
    return m_str;
}

bool String::startWith(const char *s) const
{
    bool ret = (s != nullptr);

    if (ret)
    {
        size_t len = strlen(s);

        ret = (m_length > len) && (strncmp(m_str, s, len) == 0);
    }

    return ret;
}

bool String::startWith(const String &s) const
{
    return startWith(s.str());
}

bool String::endOf(const char *s) const
{
    bool ret = (s != nullptr);

    if (ret)
    {
        size_t len = strlen(s);
        char *str = m_str + (m_length - len);

        ret = (m_length > len) && (strncmp(str, s, len) == 0);
    }

    return ret;
}

bool String::endOf(const String &s) const
{
    return endOf(s.str());
}

String &String::insert(size_t i, const char *s)
{
    if (i <= m_length)
    {
        if ((s != nullptr) || s[0] != '\0')
        {
            size_t len = strlen(s);
            char *str = reinterpret_cast<char*>(malloc(m_length + len + 1));

            if (str != nullptr)
            {
               strncpy(str, m_str, i);
               strncpy(str + i, s, len);
               strncpy(str + i + len, m_str + i, m_length - i);
               str[len + m_length] = '\0';

                free(m_str);
                m_str = str;
                m_length = m_length + len;
            }
            else
            {
                THROW_EXCEPTION(NoEnoughMemoryException, "No memory to insert str object ...");
            }
        }
    }
    else
    {
        THROW_EXCEPTION(IndexOutOfBoundsException, "Parameter i is invalid");
    }

    return *this;
}

String &String::insert(size_t i, const String &s)
{
    return insert(i, s.str());
}

String &String::trim()
{
    size_t b = 0;
    size_t e = m_length - 1;

    while (m_str[b] == ' ') b++;
    while (m_str[e] == ' ') e--;

    if (b == 0)
    {
        m_str[e + 1] = '\0';
        m_length = e + 1;
    }
    else
    {
        for (size_t i=0, j = b; j<=e; ++i, ++j)
        {
            m_str[i] = m_str[j];
        }

        m_str[e - b + 1] = '\0';
        m_length = e - b + 1;
    }

    return *this;
}

bool String::operator == (const char *s) const
{
    return (strcmp(m_str, s ? s : "") == 0);
}

bool String::operator == (const String &s) const
{
    return (strcmp(m_str, s.str()) == 0);
}

bool String::operator != (const char *s) const
{
    return (strcmp(m_str, s ? s : "") != 0);
}

bool String::operator != (const String &s) const
{
    return (strcmp(m_str, s.str()) != 0);
}

bool String::operator > (const char *s) const
{
    return (strcmp(m_str, s ? s : "") > 0);
}

bool String::operator > (const String &s) const
{
    return (strcmp(m_str, s.str()) > 0);
}

bool String::operator < (const char *s) const
{
    return (strcmp(m_str, s ? s : "") < 0);
}

bool String::operator < (const String &s) const
{
    return (strcmp(m_str, s.str()) < 0);
}

bool String::operator >= (const char *s) const
{
    return (strcmp(m_str, s ? s : "") >= 0);
}

bool String::operator >= (const String &s) const
{
    return (strcmp(m_str, s.str()) >= 0);
}

bool String::operator <= (const char *s) const
{
    return (strcmp(m_str, s ? s : "") <= 0);
}

bool String::operator <= (const String &s) const
{
    return (strcmp(m_str, s.str()) <= 0);
}

String String::operator + (const char *s) const
{
    String ret;

    size_t len = m_length + strlen(s ? s : "");

    char *str = reinterpret_cast<char*>(malloc(len + 1));

    if (str != nullptr)
    {
        strcpy(str, m_str);
        strcat(str, s ? s : "");

        free(ret.m_str);

        ret.m_str = str;
        ret.m_length = len;
    }
    else
    {
        THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create str object ...");
    }

    return ret;
}

String String::operator + (const String &s) const
{
    return (*this + s.str());
}

String &String::operator += (const char *s)
{
    return (*this = *this + s);
}

String &String::operator += (const String &s)
{
    return (*this = *this + s.str());
}

String &String::operator = (const char c)
{
    char s[] = {c, '\0'};

    return (*this = s);
}

String &String::operator = (const char *s)
{
    if (m_str != s)
    {
        char *str = strdup(s ? s : "");

        if (str != nullptr)
        {
            free(m_str);

            m_str = str;
            m_length = strlen(str);
        }
        else
        {
            THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create str object ...");
        }
    }

    return *this;
}

String &String::operator = (const String &s)
{
    return (*this = s.str());
}

char &String::operator[] (size_t i)
{
    if (i < m_length)
    {
        return m_str[i];
    }
    else
    {
        THROW_EXCEPTION(InvalidParameterExcetion, "Parameter i invalid...");
    }
}

char String::operator[] (size_t i) const
{
    return const_cast<String&>(*this)[i];
}

String::~String()
{
    free(m_str);
}

}

文件:main.cpp

输出

#include <iostream>
#include "DTString.h"

using namespace std;
using namespace DTLib;

int main()
{
    String s = "D.T.Software";

    cout << s.startWith("D.T.") << endl;
    cout << s.endOf("Software") << endl;

    for (size_t i=0; i<s.length(); ++i)
    {
        cout << s[i] << " ";
    }

    cout << "----" << endl;

    String s1 = "";
    s1.insert(0, "D.T.");
    s1.insert(4, "Software");

    cout << s1.str() << endl;

    cout << "----" << endl;

    String s2 = "  abc  ";

    if (s2.trim().insert(0, "D.T.").endOf("abc") && s2.startWith("D.T."))
    {
        cout << s2.str() << endl;
    }

    return 0;
}

输出:

1
1
D . T . S o f t w a r e ----
D.T.Software
----
D.T.abc

To be continued ...

思考:如何在目标字符串中查找是否存在指定的字串
String s = "D.T.Software";
int pos = s.indexof("Software");

以上内容整理于狄泰软件学院系列课程,请大家保护原创!


TianSong
734 声望138 粉丝

阿里山神木的种子在3000年前已经埋下,今天不过是看到当年注定的结果,为了未来的自己,今天就埋下一颗好种子吧