這樣做的辦法是去除前導空白和尾隨空白並用單個空格替換多個空格嗎?
回答該問題的最佳方法是測試它。
void Test(const char *input, const char *expected_output) {
char buffer[80];
strcpy(buffer, input);
RemoveSpace(buffer);
assert(strcmp(buffer, expected_output) == 0);
}
int main() {
Test(" Leading spaces removed.", "Leading spaces removed.");
Test("Trailing spaces removed. ", "Trailing spaces removed.");
Test("Inner spaces trimmed.", "Inner spaces trimmed.");
Test(" A little of everything. ", "A little of everything.");
Test(" \tTabs \t\tare \t spaces, too.", "Tabs are spaces, too.");
return 0;
}
在OP中的代碼沒有通過最後的測試,所以答案是沒有。
您是否認爲這是一種高效的單程解決方案?
這是一次性解決方案。如果你試圖擠出每盎司的效率,那麼你想盡量減少操作和條件分支的數量。
在C語言中使用C字符串時,通常使用指針而不是索引來使用指針。根據編譯器和目標平臺的不同,使用指針可能比索引效率更高或更低,但兩者的成本都很低。由於這已經是一次單一的線性通過,所以最好的辦法是使用慣用的代碼模式儘可能清楚地寫出它。
這裏是我的解決方案:
#include <assert.h>
#include <ctype.h>
#include <string.h>
void RemoveSpace(char *string) {
char *target = string;
char *last = target;
int skipping_spaces = 1;
for (const char *source = string; *source != '\0'; ++source) {
if (isspace(*source)) {
if (!skipping_spaces) {
*target++ = *source;
skipping_spaces = 1;
}
} else {
*target++ = *source;
last = target;
skipping_spaces = 0;
}
}
*last = '\0';
}
它本質上是一個小的狀態機,這意味着,在每一步,我們決定基於當前輸入字符和當前狀態做什麼。對於這個問題,我們的狀態就是我們是否正在跳過空格(還有一個書籤記錄最後一個結束字符串的合法點)。
由於strlen,這是兩次通過。 – 2016-02-16 15:40:00