(本博客旨在個人總結回顧)
題目描述:
請實現一個函數,把字符串中的每個空格替換成"%20"。f例如輸入"We are happy",則輸出"We%20are%20happy"
( 此題目需要問面試官是在原始字符串上移動數據,還是另外開闢空間,下面解法是在原字符串上移動字符實現字符串替換,並在字符串空間足夠的情況下。)
解決思路:
計算出一共有多少個空格就知道從字符串尾部開始往前遍歷,每一個字符串需要移動位置。
替換函數:
/*
* @name ReplaceBlack
* @brief 將字符串中空格替換爲%20(在原始字符串中移動字符,並且空間足夠不會越界)
* @param [in] char * str
* @return void
*/
void ReplaceBlack(char* str)
{
if (NULL == str)
{
return;
}
int nBlack = 0;
int nEnd = strlen(str);
for (int i = 0; i < nEnd; i++)
{
if (str[i] == ' ')
{
nBlack++;
}
}
int nIndex = nEnd + 2 * nBlack;
while (nIndex >= 0 && nIndex > nEnd)
{
if (str[nEnd] != ' ')
{
str[nIndex--] = str[nEnd--];
}
else
{
str[nIndex--] = '0';
str[nIndex--] = '2';
str[nIndex--] = '%';
nEnd--;
}
}
}
測試完整代碼:
/*
* @name ReplaceBlack
* @brief 將字符串中空格替換爲%20(在原始字符串中移動字符,並且空間足夠不會越界)
* @param [in] char * str
* @return void
*/
void ReplaceBlack(char* str)
{
if (NULL == str)
{
return;
}
int nBlack = 0;
int nEnd = strlen(str);
for (int i = 0; i < nEnd; i++)
{
if (str[i] == ' ')
{
nBlack++;
}
}
int nIndex = nEnd + 2 * nBlack;
while (nIndex >= 0 && nIndex > nEnd)
{
if (str[nEnd] != ' ')
{
str[nIndex--] = str[nEnd--];
}
else
{
str[nIndex--] = '0';
str[nIndex--] = '2';
str[nIndex--] = '%';
nEnd--;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//測試例子
char str1[100] = "We are happy";
char* str2 = NULL;
char str3[100] = "";
char str4[100] = " ";
char str5[100] = " happy";
char str6[100] = "happy ";
cout << "原字符串:" << str1 << endl;
ReplaceBlack(str1);
cout << "替換後:" << str1 << endl << endl;
ReplaceBlack(str2);
cout << "原字符串:" << str3 << endl;
ReplaceBlack(str3);
cout << "替換後:" << str3 << endl << endl;
cout << "原字符串:" << str4 << endl;
ReplaceBlack(str4);
cout << "替換後:" << str4 << endl << endl;
cout << "原字符串:" << str5 << endl;
ReplaceBlack(str5);
cout << "替換後:" << str5 << endl << endl;
cout << "原字符串:" << str6 << endl;
ReplaceBlack(str6);
cout << "替換後:" << str6 << endl << endl;
system("pause");
return 0;
}
執行結果: