c++里字符串的问题

来源:百度知道 编辑:UC知道 时间:2024/07/02 03:58:39
给定一个字符串str1,求从第n个字符开始,长度为m的子串。
如str1=“abcde”,n=2,m=2,结果为“cd”

#include<iostream.h>
#include<string.h>
#define MAX 1000
void main()
{
char str[MAX];
int m,n,i;
cout<<"请输入字符串:";
cin>>str;
int len=strlen(str);
cout<<"请输入开始字符的位置和长度:"<<endl;
cin>>n>>m;
if(n>len || m>len)
cout<<"出错"<<endl;
else
{
for(i=n;i<m+n;i++)
cout<<str[i];
cout<<endl;
}
}

不知道楼主定义的字符串变量str1的具体类型,如果定义为string类型,则:
string str1 = "abcde";
cout << str1.substr(2, 2); // 输出cd