A Journey 2 Eternity

Replace all spaces in a string with some characters

Posted on: July 13, 2012

We are going to write a method to replace all spaces in a string with “%20”. We assume that the string have sufficient space.

void ReplaceSpaces(char *str) 
{
	int length = strlen(str);
	int nSpaces = 0, newLength = 0;
	for (int i = 0; i < length; i++)
	{
		if(str[i] == ' ') ++nSpaces;
	}

	newLength = length + nSpaces * 2;
	str[newLength] = '\0';

	for (int i = length - 1 ; i >= 0; i--)
	{
		if (str[i] == ' ')
		{
			str[newLength - 1] = '0';
			str[newLength - 2] = '2';
			str[newLength - 3] = '%';
			newLength -= 3;
		} else {
			str[newLength - 1] = str[i];
			newLength -= 1;
		}
	}
}
Advertisements
Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

July 2012
M T W T F S S
« Jun   Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Blog Stats

  • 27,486 hits
%d bloggers like this: