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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Truncatng

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
 
use strtok:

char *s1, *s2, *s3, *s4 ;

s1 = strtok( wholestring, " " ) ;
s2 = strtok( NULL, " " ) ;
s3 = strtok( NULL, " " ) ;
s4 = strtok( NULL, " " ) ;

sprintf( partone, "%s %s", s1, s2) ;
sprintf( parttwo, "%s %s", s3, s4) ;
 
Do like this:

Code:
#include <stdio.h>
#include <string.h>
#include <memory.h>

#define WHOLE_LNG 60 //the length of the whole string
#define PART1_LNG 30 //the lenght of first part
#define PART2_LNG 30 //the lenght of second part

#define DELIMIT_SPACE 2 //indicates which space is considered delimiter

int main()
{
	char wholestring[WHOLE_LNG];
	char partone[PART1_LNG];
	char parttwo[PART2_LNG];

	strcpy(wholestring, &quot;Sacramento Richardson Montreal Vancouver&quot;);
	memset(partone, 0, PART1_LNG);
	memset(parttwo, 0, PART2_LNG);

	int i = 0; //index
	int skipped = 0; //counts the number of spaces skipped
	while( i < WHOLE_LNG && skipped < DELIMIT_SPACE ){
		if( wholestring[i++] == ' ' )
			skipped++;
	}
	
	//i indicates the delimiter position
	strncpy(partone, wholestring, --i < PART1_LNG ? i : PART1_LNG);
	//as a prevention make sure the last char is NULL
	partone[PART1_LNG - 1]	= 0;

	int aux	= WHOLE_LNG - i - 1;
	strncpy(partone, wholestring + i + 1, PART2_LNG < aux ? PART2_LNG : aux);
	parttwo[PART2_LNG - 1]	= 0;
	
	return 0;
}

 
Oh, si too difficult. See function WinAPI function SetEndOfFile Ion Filipski
1c.bmp


filipski@excite.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top