1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int num_of_words(char* string)
{
int counter=1,i;
for(i=0;string[i]!='\0';i++)
{
if(string[i]==' ')
counter++;
}
return counter;
}
void string_split(char* string,char** dp,int lgt,int n) //string,dp,length,num_of_words
{
int i,j;
for(i=0,j=0;i<lgt && j<n;i++)
{
char test[50];
if(i==0&&j==0)
{
for(int x=0;string[x]!=' ';x++)
{
test[x]=string[x];
}
cout<<"TEST LENGTH IS"<<strlen(test);
dp[0]=new char[strlen(test)+1];
// dp[0]=test;
strcpy(dp[0],test);
cout<<dp[0];
cout<<"Split"<<endl;
j++;
}
if(string[i]==' ')
{
i++;
for(int k=i,l=0;string[k]!=' ';k++,l++)
{
test[l]=string[k];
}
dp[j]=new char[strlen(test)+1];
// dp[j]=test;
strcpy(dp[j],test);
cout<<"Split "<<j<<" "<<dp[j]<<endl;
j++;
}
}
}
int main()
{
char** dpointer;
cout<<"Enter a string"<<endl;
char string[50];
gets(string);
int a=num_of_words(string);
dpointer=new char*[a];
cout<<"The number of words are "<<a<<endl;
char* tpointer=string;
string_split(string,dpointer,strlen(string),a);
for(int y=0;y<a;y++)
{
delete[] dpointer[y];
}
delete[] dpointer;
getch();
return 0;
}
|