面试题5:替换空格
题目:
请实现一个函数,把字符串中的每个空格替换成“%20”。例如,输入“We are happy.”则输出“We%20are%20happy”
思路 先计算所有空格数,然后按照所有空格数的数量实现计算出最后一个字符所在位置,再从后往前遍历用两个指针复制字符,如果遇到空格就将代替字符写入,直到两个指针相等。
#include "stdafx.h"
#include <string>
void ReplaceBlank ( char * string, unsigned int length)
{
if ( string == nullptr || length < 1 )
return ;
int i = 0 ;
unsigned int blankCount = 0 ;
unsigned int originalLength = 0 ;
while ( string[ i] != '\0' )
{
originalLength++ ;
if ( string[ i] == ' ' )
blankCount++ ;
i++ ;
}
unsigned newLength = originalLength + blankCount* 2 ;
if ( newLength > length)
return ;
int indexOfNew = newLength;
int indexOfOriginal = originalLength;
while ( indexOfOriginal >= 0 && indexOfNew> indexOfOriginal)
{
if ( string[ indexOfOriginal] == ' ' )
{
indexOfOriginal-- ;
string[ indexOfNew-- ] = '0' ;
string[ indexOfNew-- ] = '2' ;
string[ indexOfNew-- ] = '%' ;
}
else
string[ indexOfNew-- ] = string[ indexOfOriginal-- ] ;
}
}
void Test ( char * testName, char str[ ] , int length, char expected[ ] )
{
if ( testName != nullptr )
printf ( "%s begins: " , testName) ;
ReplaceBlank ( str, length) ;
if ( expected == nullptr && str == nullptr )
printf ( "passed.\n" ) ;
else if ( expected == nullptr && str != nullptr )
printf ( "failed.\n" ) ;
else if ( strcmp ( str, expected) == 0 )
printf ( "passed.\n" ) ;
else
printf ( "failed.\n" ) ;
}
void Test1 ( )
{
const int length = 100 ;
char str[ length] = "hello world" ;
Test ( "Test1" , str, length, "hello%20world" ) ;
}
void Test2 ( )
{
const int length = 100 ;
char str[ length] = " helloworld" ;
Test ( "Test2" , str, length, "%20helloworld" ) ;
}
void Test3 ( )
{
const int length = 100 ;
char str[ length] = "helloworld " ;
Test ( "Test3" , str, length, "helloworld%20" ) ;
}
void Test4 ( )
{
const int length = 100 ;
char str[ length] = "hello world" ;
Test ( "Test4" , str, length, "hello%20%20world" ) ;
}
void Test5 ( )
{
Test ( "Test5" , nullptr , 0 , nullptr ) ;
}
void Test6 ( )
{
const int length = 100 ;
char str[ length] = "" ;
Test ( "Test6" , str, length, "" ) ;
}
void Test7 ( )
{
const int length = 100 ;
char str[ length] = " " ;
Test ( "Test7" , str, length, "%20" ) ;
}
void Test8 ( )
{
const int length = 100 ;
char str[ length] = "helloworld" ;
Test ( "Test8" , str, length, "helloworld" ) ;
}
void Test9 ( )
{
const int length = 100 ;
char str[ length] = " " ;
Test ( "Test9" , str, length, "%20%20%20" ) ;
}
int main ( int argc, char * argv[ ] )
{
Test1 ( ) ;
Test2 ( ) ;
Test3 ( ) ;
Test4 ( ) ;
Test5 ( ) ;
Test6 ( ) ;
Test7 ( ) ;
Test8 ( ) ;
Test9 ( ) ;
return 0 ;
}