first, analyze the idea of the program :
1: start with the first element of S, match the 1th element in T, and if equal, match the i+1 element of s with the 2nd element in T, and so on, if all elements of T match, then return position I; otherwise, execute 2;
2: i++; If the first element of S is ' + ', that is, the string terminator, stop execution; otherwise, repeat step 1.
Next, give the program :
#include <iostream> //storage of input/output streams
#include <cstdio> //storage of puts and gets functions
using namespace Std; //Using namespaces
int index (char *p,char *q) //Definition of function
{
Char *a;char *b;
int num=1; //Used to record the number of positions
while (*p!= ') //P string-by-distinction
{
c=2; //Use a, B to replace P and Q respectively
b=q;
while (*b!= ' &&*a!= ' &&*b==*a) //If the corresponding elements are equal and neither of the two strings is to the Terminator
{
a++;
b++;
}
if (*b== ') //If matched, then B corresponds to ' \ s ' Terminator
return num;
num++; //Position plus 1, remove an elemental analysis
p++;
}
return-1; //Otherwise, return-1
}
void Main ()
{
while (1) //Can be used to test the results of the program indefinitely
{
Char *s=new char[100];
Char *t=new char[50];
cout<< "Please enter string s:" <<endl;
Gets (s); //The acquired string is stored in the character pointer
cout<< "Please enter string T:" <<endl;
Gets (t); //The acquired string is stored in the character pointer
int N=index (S,T);
if (n==-1)
cout<<t<< "Not in" <<s<< "! "<<endl;
Else
cout<<t<< "<<n<<" in "<<s<<" in the left! "<<endl;
}
}
The result of the final program operation:
You can see the effect is good, whether it is a word or a string, both meet the requirements.
Writes the function int index (char *s,char * t) in the C + + language, returns the leftmost position where the string T appears in the string s, and returns 1 if there is no substring matching t in S. Features that are similar to indexes.