编程论坛
注册
登录
编程论坛
→
C++教室
字符串的问题
梦ambious
发布于 2012-06-12 15:14, 384 次点击
假定给一个string类字符串,要想节取中间的一段该怎么弄?谢谢了
2 回复
#2
zxwangyun
2012-06-12 15:27
程序代码:
#include
<iostream>
#include
<string>
using
namespace
std;
bool
get_substr(
const
string
& str,
int
pos
/*
截取位置,0开始
*/
,
unsigned
int
length
/*
截取长度
*/
,
char
** lpsubstr
/*
out
*/
)
{
if
(pos >= str.length())
return
false
;
if
(pos + length >= str.length())
length = str.length() - pos;
*lpsubstr =
new
char
[length+
1
];
if
(!*lpsubstr)
return
false
;
memset(*lpsubstr,
0
,length+
1
);
memcpy(*lpsubstr,&str.c_str()[pos],length);
return
true
;
}
int
main()
{
string
str(
"
1234567890
"
);
char
* psubstr = NULL;
if
(get_substr(str,
7
,
5
,&psubstr) && psubstr)
{
cout
<<psubstr<<endl;
delete
[] psubstr;
psubstr = NULL;
}
system(
"
pause
"
);
return
0
;
}
#3
lonmaor
2012-06-12 17:17
http://www.
public member function
string::substr
Example:
程序代码:
//
string::substr
#include <iostream>
#include
<string>
using
namespace
std;
int
main ()
{
string
str=
"
We think in generalities, but we live in details.
"
;
//
quoting Alfred N. Whitehead
string
str2, str3;
size_t pos;
str2 = str.substr (
12
,
12
);
//
"generalities"
pos = str.find(
"
live
"
);
//
position of "live" in str
str3 = str.substr (pos);
//
get from "live" to the end
cout
<< str2 <<
'
'
<< str3 << endl;
return
0
;
}
1