获取子串时,输入空格就会有乱码,倒腾半天才知道接受母串时出错,cin.get(S,MAX_STRLEN); 不能接受空格回车之类的,gets()可以实现。小问题,害的自己狂晕。还是基础不行啊。
-
#include <stdio.h>用静态数组实现求子串(SubString)操作。从屏幕输入:
主串"Life is like a box of chocolate!"
子串的位置
子串长度
输出子串"a box of chocolate!"。 - #include <iostream.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_STRLEN 255
- typedef char SString[MAX_STRLEN+1];
- int SubString (SString &Sub,SString S,int pos,int len)
- {
- if (pos<1||pos>S[0]||len<0||len>S[0]-pos+1)
- {
- cout<<"Error"<<endl;
- return 0;
- }
- for (int i=1;i<=len;i++)
- {
- Sub[i]=S[pos+i-1];
- }
- Sub[0]=len;
- Sub[i]='/0';
- return 1;
- }
- int main()
- {
- char Sub[MAX_STRLEN+1];
- int pos,len;
- char S[MAX_STRLEN+1];
- for (int i=0;i<MAX_STRLEN;i++)
- {
- cout<<"SubString.cpp/n=============/n/n"<<endl;
- cout<<"Please input the main String:"<<endl;
- gets(S);
- //cin.get(S,MAX_STRLEN);
- cout<<"Please input the position and length of SubString:"<<endl;
- cout<<"position="<<endl;
- cin>>pos;
- cout<<"length="<<endl;
- cin>>len;
- if(SubString(Sub,S,pos,len))
- {
- cout<<"The SubString is_="<<Sub+1<<endl;
- //cout<<"SubString.length= "<<Sub[0]<<endl;
- printf("SubString.length= %d/n",Sub[0]);
- }
- getchar();
- Sub[i]=NULL;
- S[i]=NULL;
- }
- return 0 ;
- }