2
A
回答
7
這種方法很好。 O(n)的要求僅僅意味着運行時間與在這種情況下表示字符串中字符的數量成正比(假設您的意思是時間複雜度,這是一個相當安全的下注)。
的僞代碼:
def removeSpaces (str):
src = pointer to str
dst = src
while not end-of-string marker at src:
if character at src is not space:
set character at dst to be character at src
increment dst
increment src
place end-of-string marker at dst
基本上是你想要做什麼。
因爲它有一個依賴於字符數的單一循環,所以它確實是O(n)時間複雜度。
下面的C程序顯示了這個動作:
#include <stdio.h>
// Removes all spaces from a (non-const) string.
static void removeSpaces (char *str) {
// Set up two pointers.
char *src = str;
char *dst = src;
// Process all characters to end of string.
while (*src != '\0') {
// If it's not a space, transfer and increment destination.
if (*src != ' ')
*dst++ = *src;
// Increment source no matter what.
src++;
}
// Terminate the new string.
*dst = '\0';
}
// Test program.
int main (void)
{
char str[] = "This is a long string with lots of spaces... ";
printf ("Old string is [%s]\n", str);
removeSpaces (str);
printf ("New string is [%s]\n", str);
return 0;
}
運行這給你:
Old string is [This is a long string with lots of spaces... ]
New string is [Thisisalongstringwithlotsofspaces...]
需要注意的是,如果沒有在嚴格的空間克,它只是複製每一個字符。你可能會認爲你可以通過檢查是否優化它,而不是複製,但你可能會發現這個檢查和拷貝一樣貴。而且,除非您經常複製數兆字節的字符串,否則性能不會成爲問題。
也請記住,這將是未定義的行爲與const
字符串,但這將是在任何就地修改的情況下。
3
你的方法聽起來不錯,並滿足使用要求。
相關問題
- 1. 在JavaScript中刪除字符串中的第(n)個空格
- 2. 如何刪除字符串中的所有空格和\ n \ r?
- 3. 刪除Java字符串中的空格?
- 4. 刪除字符串中的空格Javascript
- 5. 刪除字符串中的空格
- 6. 刪除字符串中的空格
- 7. 刪除字符串中的空格
- 8. 刪除XML字符串中的空格
- 9. Python - 刪除字符串中的空格
- 10. 刪除Python字符串中的空格
- 11. 刪除字符串中的空格
- 12. 刪除字符串中的空格
- 13. 從長字符串空格中刪除單個空格字符
- 14. 只從字符串中刪除空格
- 15. awk從字符串中刪除空格
- 16. QStringList從字符串中刪除空格
- 17. 從字符串中刪除空格
- 18. 從字符串中刪除空格
- 19. 從字符串中刪除空格
- 20. 如何刪除字符串中的\ n?
- 21. 刪除字符串,除非有空格
- 22. 刪除python中的字符串中的空格和製表符
- 23. 從字符串中刪除'\ t'和'\ n'
- 24. 從字符串中刪除「\ n \」
- 25. 如何從iphone中的字符串中刪除刪除/ n/t
- 26. Shell腳本:刪除字符串中的所有空格字符
- 27. 從字符串中刪除空格以外的特殊字符
- 28. C - 刪除字符串中特定字符的空格
- 29. 刪除字符串和空格中的多個字符
- 30. 刪除Rails中字符串的所有空格字符
可能的重複[從C中的字符串中刪除空格?](http://stackoverflow.com/questions/1726302/removing-spaces-from-a-string-in-c) – bdonlan 2010-06-22 04:52:29