Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Truncating

Status
Not open for further replies.

htakeda

IS-IT--Management
Sep 26, 2001
3
US
Is there a way to cut strings? If I have
char wholestring[60];
char partone[30];
char parttwo[30];
strcpy (wholestring, "begin part end part");
is there a way to cut the string so that I have partone = "begin part" and parttwo = "end part"?
Also, I want to use the second space (" ") as a divider. So in another case where you have
strcpy(wholestring, "Sacramento Richardson Montreal Vancouver");
I would want
partone = "Sacramento Richardson"
parttwo = "Montreal Vancouver"
regards,
Hiro
 
Or if you're doing a lot of string stuff, try using the C++ Standard Library string class.

Your example for second blank could look like this:

string partone;
string parttwo;

string in = "Thisis astring withblanks inthemiddle";


int n = in.find(' ');
n = in.find(' ',n+1);
partone = in.substr(0,n);
parttwo = in.substr(n+1,in.size()-n);

If you wanted to check that the string was as expected (and adding a few "official" frills):

string::size_type n = in.find(' ');
if (n!=string::npos) n = in.find(' ',n+1);
if (n!=string::npos)
{
partone = in.substr(0,n);
parttwo = in.substr(n+1,in.size()-n);
}

Then you could put them back together again with

string out = partone + ' ' + parttwo;

for example.
 
Here's a super-manual way. p will point to the first and q to the second. If there are less than two spaces (or no spaces), q will point to the end of the string.
Code:
#include <iostream.h>

int main()
{
	char* p = &quot;begin part end part&quot;;
	char* q = p;
	int i = 0;
	
	while (*q != 0)
	{
		if(*q == ' ') i++;
		q++;
		if(i == 2){*(q - 1) = 0; break;}
	}
	cout << p << endl << q;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top