In: Computer Science
I am trying to return a string from certain position of the sentence on C++, like a function/ statement that is equivalent to excel mid function.
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
string str ;
cout<<"Enter sentence"<<endl;
getline (cin, str);//to read a line with spaces
int pos;
cout<<"Enter position from where you want to get
the string"<<endl;
cin>>pos;
int len=str.size();
if(len<pos||pos<=0)
{
cout<<"Invalid
position"<<endl;
exit(0);
}
int i=pos-1;
cout<<"String from position "<<pos<<" is =>
";
if(str[i]==' '||str[i]==' ')
{
i++;
}
//break when you find terminating, space, tab or new line
character
while(str[i]!='\n'&&str[i]!='
'&&str[i]!=' '&&str[i]!='\0')
{
cout<<str[i];
i++;
}
cout<<endl;
cout<<"Sentence from position "<<pos<< " is =>
";
cout<<str.substr(pos-1,len-1);
cout<<endl;
return 0;
}
output 1-
Enter sentence
Hello Frank! What's going on?
Enter position from where you want to get the string
6
String from position 6 is => Frank!
Sentence from position 6 is => Frank! What's going on?
output 2-
Enter sentence
Hello Frank! What's going on?
Enter position from where you want to get the string
7
String from position 7 is => Frank!
Sentence from position 7 is => Frank! What's going on?