문자열의 기본 기능 구현
1. MyString s1 ( "asdf")를 사용하여 문자열 개체를 만듭니다.
2. MyString s2 ( 'c', 5)를 사용하여 "ccccc"를 만듭니다.
3. MyString s3 (100)을 사용하여 문자열 "100"을 만듭니다. "
4. 문자열의 길이를 가져옵니다.
5. 문자열을 출력합니다 .
6. 하위 문자열과 문자를 찾습니다.
Main.cpp
#include"MyString.h"
#include<iostream>
#include<random>
#include<string>
#include<vector>
using namespace std;
int main(){
MyString mystr("abcdefghijklmn");
mystr.toString();
MyString mystr2("10");
mystr2.toString();
const char x = 'a';
MyString mystr3(x,5);
mystr3.toString();
//vector<int> res = mystr.findOne('f');
vector<int> res = mystr.findAll("jk1");
for (int i = 0;i<res.size();i++)
{
cout<<res[i]<<endl;
}
cout<<""<<endl;
MyString mystr2(100);
mystr2.toString();
return 0;
}
MyString.h
#include<iostream>
#include<vector>
using namespace::std;
class MyString
{
private:
const char *str;
int length = 0;
public:
MyString(const char pstr[]);
MyString(const char x,int length);
MyString(int x);
~MyString();
void toString();
int my_strlen(const char *str);
int getLength();
vector<int> findOne( char x);
vector<int> findAll(const char x[]);
};
MyString.cpp
#include<iostream>
#include"MyString.h"
#include<random>
#include<string>
#include"vector"
#include<stdio.h>
#include<stdlib.h>
using namespace std;
MyString::MyString(const char pstr[]){
while(pstr[length]!='\0'){
length++;
}
char *help= new char[length];
for (int i = 0; i < length; i++){
help[i] = pstr[i];
}
str = help;
}
MyString::MyString(int x){
vector<char> re;
while(x>9){
int res = x%10;
char ress = res+'0';
re.push_back(ress);
x = x/10;
}
re.push_back(x+'0');
length = re.size();
cout<<length<<endl;
char *w = new char[length];
int index = length-1;
int second_index = 0;
while(index>=0){
w[second_index] = re[index];
index--;
second_index++;
}
str = w;
}
MyString::MyString(const char x,int length){
char *help= new char[length];
for (int i = 0; i < length; i++){
help[i] = x;
}
str = help;
this->length = length;
}
MyString::~MyString(){
}
void MyString::toString(){
cout<<""<<endl;
for (int i = 0; i < length; i++){
cout<< *(str+i);
}
cout<<""<<endl;
}
int MyString::getLength(){
return length;
}
vector<int> MyString::findOne( char x){
vector<int> result;
for (int i = 0; i < length; i++){
if(*(str+i) == x){
result.push_back(i);
}
}
cout<<""<<endl;
return result;
}
vector<int> MyString::findAll(const char x[]){
vector<int> res;
int len = 0;
while(x[len]!='\0'){
len++;
}
int end = length - len;
for (int i = 0; i <= end; i++){
bool flags = true;
int j = i;
int index = 0;
while(index<len&&j<i+len){
if(str[j]!= x[index]){
flags = false;
}
index++;
j++;
}
if(flags){
res.push_back(i);
}
}
if(res.empty()){
cout<<"未找到该字符串"<<endl;
}
return res;
}
Ubuntu 환경에서 스크립트 컴파일
#!/bin/bash
g++ -c Main.cpp
g++ -c MyString.cpp
g++ Main.o MyString.o -o result
./result
rm Main.o MyString.o result
./result를 실행 한 후 스크립트와 3 개의 파일을 같은 디렉토리 ./script 이름에 넣으면 실행 결과를 볼 수 있습니다.