C++ experiment --- subscript operation of custom strings

Subscript operation of custom strings

Description

Define the class MyString, which is composed of strings with a length of no more than 100. Overload its subscript operator:

Used to repeatedly find the subscript of the specified character ch in the string.

Overload its input operator for input string.

Input

Enter a string (with no more than 100 characters) and one character without white space.

Output

Specify all positions of the character in the string.

Sample Input

babababaab a

Sample Output

1
3
5
7
8
-1

HINT

Static variables are needed in the subscript operator.

It is forbidden to use STL, including list, vector, string, etc.

Title given code

int main()
{
    
    
    MyString mystr;
    char c;
    int pos;
    cin>>mystr>>c;
    do{
    
    
        pos = mystr[c];
        cout<<pos<<endl;
    }while(pos != -1);
    return 0;
}

code:

#include<iostream>
#include<stdio.h>
#include<string.h>

using namespace std;
int index=0;//设置全局变量

class MyString{
    
    
	char s[101];
public:
	friend istream& operator >>(istream &is,MyString &M){
    
    
		char c=getchar();
		int len=0;
		while(c!=' '){
    
    
			M.s[len++]=c;
			c=getchar();
		}	
		M.s[len]='\0';
		return is;
	}
	
	int operator[](char c){
    
    
		int i=index;
		for(;i<100&&s[i]!='\0';i++){
    
    
			if(c==s[i]){
    
    
				break;
			}
		}
		if(i==100||s[i]=='\0'){
    
    
			return -1;
		}else{
    
    
			index=i+1;
			return i;
		}
	}
};

int main()
{
    
    
    MyString mystr;
    char c;
    int pos;
    cin>>mystr>>c;
    do{
    
    
        pos = mystr[c];
        cout<<pos<<endl;
    }while(pos != -1);
    return 0;
}

Guess you like

Origin blog.csdn.net/timelessx_x/article/details/115092052