一个简单的关于string的有关问题,高手指教一下
一个简单的关于string的问题,高手指教一下!
我的目标是想把一个字符串以空格为标志,分成几个子串,存在另外的一个字符串数组中,也可以用char数组实现,大家帮我!
#include <iostream>
#include <string>
using namespace std;
int main(){
string order;
cout < < "Please input the orders: " < <endl;
cin> > order;
char* p=order;
int first=0;
int last=0;
string a[10];
int i=0;
while(p!=NULL){
if(*p== ' '){
if(first!=last){
a[i]=order.Substring(first,last);
}
else
p++;
first=last+1;
last=first;
}
else{
p++;
last++;
}
}
for(int j=0;j <i;j++)
cout < <a[j] < <endl;
return 0;
}
------解决方案--------------------
参考一下这个 msdn中的例子
// crt_strtok.c
// compile with: /W1
// In this program, a loop uses strtok
// to print all the tokens (separated by commas
// or blanks) in the string named "string ".
//
#include <string.h>
#include <stdio.h>
char string[] = "A string\tof ,,tokens\nand some more tokens ";
char seps[] = " ,\t\n ";
char *token;
int main( void )
{
printf( "Tokens:\n " );
// Establish string and get the first token:
token = strtok( string, seps ); // C4996
// Note: strtok is deprecated; consider using strtok_s instead
while( token != NULL )
{
// While there are tokens in "string "
printf( " %s\n ", token );
// Get next token:
token = strtok( NULL, seps ); // C4996
}
}
我的目标是想把一个字符串以空格为标志,分成几个子串,存在另外的一个字符串数组中,也可以用char数组实现,大家帮我!
#include <iostream>
#include <string>
using namespace std;
int main(){
string order;
cout < < "Please input the orders: " < <endl;
cin> > order;
char* p=order;
int first=0;
int last=0;
string a[10];
int i=0;
while(p!=NULL){
if(*p== ' '){
if(first!=last){
a[i]=order.Substring(first,last);
}
else
p++;
first=last+1;
last=first;
}
else{
p++;
last++;
}
}
for(int j=0;j <i;j++)
cout < <a[j] < <endl;
return 0;
}
------解决方案--------------------
参考一下这个 msdn中的例子
// crt_strtok.c
// compile with: /W1
// In this program, a loop uses strtok
// to print all the tokens (separated by commas
// or blanks) in the string named "string ".
//
#include <string.h>
#include <stdio.h>
char string[] = "A string\tof ,,tokens\nand some more tokens ";
char seps[] = " ,\t\n ";
char *token;
int main( void )
{
printf( "Tokens:\n " );
// Establish string and get the first token:
token = strtok( string, seps ); // C4996
// Note: strtok is deprecated; consider using strtok_s instead
while( token != NULL )
{
// While there are tokens in "string "
printf( " %s\n ", token );
// Get next token:
token = strtok( NULL, seps ); // C4996
}
}