In: Computer Science
Solution:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
//Declaring C style string
char line[]="ls -l -a | wc -c >> myfile";
size_t len;
//Finding length of string 'line'
len=strlen(line);
//Printing the length of string
cout<<"The length of 'line' is "<<len<<endl;
//Declaring an array of C-strings
char* strArray[10];
int i=0;
//Initializing each string to \0
while(i<10)
{
strArray[i]=(char *)"\0";
i++;
}
int pieces;
pieces=0;
char* ptr;
//breaking line into tokens based on delimiter " "
ptr=strtok(line," ");
while(ptr!=NULL)
{
strArray[pieces]=ptr;
ptr=strtok(NULL," ");
pieces=pieces+1;
}
//Printing contents of strArray
for(i=0;i<pieces;i++)
cout<<"strArray["<<i<<"] = "<<strArray[i]<<endl;
//Finding sum of lengths of all strings in strArray
size_t size=0;
for(i=0;i<pieces;i++)
size=size+strlen(strArray[i]);
//Finding number of blanks in line
size_t numBlanks=pieces-1;
cout<<"The number of blanks is "<<numBlanks<<endl;
char* result = new char[size+1];
result[0]='\0';
//Concatenating all strings in strArray into a big string
for(i=0;i<pieces;i++)
strcat(result,strArray[i]);
//Printing the result
cout<<"The concatenation of all strings in strArray is: "<<result;
delete[] result;
return 0;
}
Output: