面试题3:替换空格和清除空格 (二)

2014-11-23 22:30:51 · 作者: · 浏览: 16
码:

#include "stdafx.h"   
#include    
using namespace std;  
  
//清除字符串str中多余的空格,从前往后遍历   
void DeleteRedundantBlank(char *str)  
{  
    if (str == NULL)  
    {  
        return;  
    }  
  
    char *p1 = str;  
    char *p2 = str;  
    bool keepBlank = false;//记录空格是否保存      
  
    while (*p1 != '\0')//注意此处应该是p1,不是p2,因为'\0'仍然需要赋给p1   
    {         
        if (*p2 != ' ')  
        {  
            *(p1++) = *(p2++);  
            keepBlank = true;  
        }  
        else  
        {  
            if (keepBlank)  
            {  
               *(p1++) = *(p2++);  
               keepBlank = false;  
            }  
            else  
            {  
               p2++;  
            }             
        }         
    }  
  
    int nlen = strlen(str);  
    if (str[nlen - 1] == ' ')  
    {  
        str[nlen - 1] = '\0';  
    }  
    nlen = strlen(str);  
}  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    char str1[50] = "We are happy.";  
    DeleteRedundantBlank(str1);  
    cout << str1 << endl;  
    cout << strlen(str1) << endl;  
  
    char str2[50] = "   We    are    happy.    ";  
    DeleteRedundantBlank(str2);  
    cout << str2 << endl;  
    cout << strlen(str2) << endl;  
  
    char str3[50] = "";  
    DeleteRedundantBlank(str3);  
    cout << str3 << endl;  
  
    char str4[50] = "    ";  
    DeleteRedundantBlank(str4);  
    cout << str4 << endl;  
  
    system("pause");  
    return 0;  
}  
#include "stdafx.h"
#include 
using namespace std; //清除字符串str中多余的空格,从前往后遍历 void DeleteRedundantBlank(char *str) { if (str == NULL) { return; } char *p1 = str; char *p2 = str; bool keepBlank = false;//记录空格是否保存 while (*p1 != '\0')//注意此处应该是p1,不是p2,因为'\0'仍然需要赋给p1 { if (*p2 != ' ') { *(p1++) = *(p2++); keepBlank = true; } else { if (keepBlank) { *(p1++) = *(p2++); keepBlank = false; } else { p2++; } } } int nlen = strlen(str); if (str[nlen - 1] == ' ') { str[nlen - 1] = '\0'; } nlen = strlen(str); } int _tmain(int argc, _TCHAR* argv[]) { char str1[50] = "We are happy."; DeleteRedundantBlank(str1); cout << str1 << endl; cout << strlen(str1) << endl; char str2[50] = " We are happy. "; DeleteRedundantBlank(str2); cout << str2 << endl; cout << strlen(str2) << endl; char str3[50] = ""; DeleteRedundantBlank(str3); cout << str3 << endl; char str4[50] = " "; DeleteRedundantBlank(str4); cout << str4 << endl; system("pause"); return 0; }