[英]Remove/Count spaces in a string (using the same string)
我有一個簡單的問題要解決:
讀取一個字符串,打印沒有空格的字符串和空格數。
我可以使用2個字符串執行此操作,一個用於存儲用戶字符串,另一個用於存儲相同的字符串而不包含空格。 但我想只使用一個字符串。
到目前為止我所擁有的:
while(str[i] != '\0'){
if(str[i] == ' '){
contEsp += 1;
}else{
strcpy(&str[i - contEsp], &str[i]);
}
i++;
}
問題:
它不計算空格數。
如果用戶鍵入雙倍或更多空間,則程序不會計數,也不會刪除空格。
問題:
我的代碼有問題嗎?
是否可以只使用一個字符串來完成此操作?
試試這段代碼:
int i = 0, contEsp =0;
while(str[i] != '\0')
{
str[i-contEsp] = str[i];
if(str[i] == ' ')
contEsp++;
i++;
}
str[i-contEsp] = '\0';
printf("String: %s, Spaces = %d\n",str, contEsp);
1)最后的空間也不要削減。 循環后添加檢查和操作。
2)我建議划分當地空間計數器和全球空間計數器的概念。
unsigned int contEsp = 0;
unsigned int i = 0;
unsigned int localEsp = 0;
while(str[i] != '\0'){
if(str[i] == ' '){
contEsp += 1;
localEsp += 1;
}else if(contEsp) {
strcpy(&str[i - localEsp], &str[i]);
localEsp = 0;
continue;
}
i++;
}
if ( localEsp > 0 )
strcpy(&str[i - contEsp], &str[i]);
由於問題標記為“性能”:您的方法是在遇到空間時復制整個剩余字符串。 雖然實際上可能無關緊要,但效率低下。 只需逐個處理字符,例如:
unsigned remove_count_spaces(char *a) {
char *b = a;
unsigned ct = 0;
do {
if (*a == ' ') ct++;
else *b++ = *a;
} while(*a++);
return ct;
}
...加上檢查ct
可能的環繞。
char* RemoveAndCountSpaces(char* s)
{
int contEsp = 0;
char* x = s;
char* org = s;
while(*s != '\0'){
if(*s == ' '){
contEsp++;
} else {
*x = *s;
x++;
}
s++;
}
*x = *s;
printf("%s\nSpaces Found: %d\n", org, contEsp);
return org;
}
我的代碼有問題嗎?
1.計數未初始化為0
2. strcpy(&str[i - contEsp], &str[i]);
正在移動尚待處理的字符串,然后你的i
不會為你想到的字符編制索引。
只使用一個字符串就可以做到這一點?
是的 - 下面
int CountAndBlank(char *str) {
size_t x = 0; /* index through un-spaced string */
size_t i; /* Index through original string */
for (i = 0; str[i]; i++) {
if (!str[i] == ' ') {
str[x++] = str[i];
}
}
str[x] = '\0';
return i - x; /* Spaces removed is the difference */
}
...
int Count = CountAndBlank(buf);
printf("Number of spaces removed from '%s' is %d\n", buf, Count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.