This repository has been archived on 2023-05-13. You can view files and clone it, but cannot push or open issues or pull requests.
mipt_cpp/seminar03_initialization/08_stringview/miptstringview.cpp
2022-10-22 19:15:34 +03:00

86 lines
1.8 KiB
C++

#pragma once
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
using std::cout, std::cin, std::endl, std::size_t;
namespace mipt {
class StringView
{
private:
const char* mpData;
size_t mSize;
public:
StringView() {;
mSize = 0;
mpData = nullptr;
}
StringView(const StringView& str) {
mSize = str.mSize;
mpData = str.mpData;
}
StringView(const mipt::String& s) {
mSize = s.getSize();
mpData = s.cStr();
}
StringView(const char* s) {
mpData = s;
mSize = strlen(s);
}
const char& at(size_t i)
{
if (i >= mSize)
{
throw std::out_of_range("Error! Index is out of bounds.");
std::exit(1);
}
return mpData[i];
}
const char& operator[](size_t i)
{
return mpData[i];
}
bool operator<(const StringView& right) const
{
size_t i = 0;
while (i < mSize && i < right.mSize && mpData[i] == right.mpData[i])
i++;
return mpData[i] < right.mpData[i];
}
size_t size() {
return mSize;
}
StringView substr(size_t pos, size_t count) {
if (pos > mSize)
throw std::out_of_range("Error! Index is out of bounds.");
if (pos + count > mSize)
count = mSize - pos;
StringView result;
result.mpData = mpData + pos;
result.mSize = count;
return result;
}
void remove_prefix(size_t n) {
mSize -= n;
}
void remove_suffix(size_t n) {
mSize -= n;
mpData += n;
}
};
};
std::ostream& operator<<(std::ostream& out, mipt::StringView sv) {
size_t size = sv.size();
for (int i = 0; i < size; ++i)
out << sv[i];
return out;
}