当前位置:编程学习 > Delphi >>

面试题目搜集

1.字符串取出多余的空格,包括行首的空格,单词与单词之间只能有多余的空格,结尾不能有空格。

例如:“    i am     lsj     ”  ==》“i am lsj”


[cpp] 
#include<iostream>  
#include<cctype>  
using namespace std; 
 
void deleteSpace(char* str) 

    char *ptr = str; 
    bool flag = true; 
    while(isspace(*str++));//去除字符串开始的空格  
    --str; 
    while(*str){ 
        if(isalpha(*str)){ 
            if(ptr != str)//防止同一个空间赋值  
                *ptr++ = *str; 
            flag = true; 
        } 
        else{ 
            if(flag){ 
                *ptr++ = *str; 
                flag = false; 
            } 
        } 
        str++; 
    } 
    ptr--;//ptr已经被加1了,特别注意  
    if(isspace(*ptr)) //去除结尾的空格  
        *ptr = '\0'; 
    else 
        *++ptr = '\0'; 
}; 
 
int main() 

    char str[]="  i am lsj   ";  
    //这里不能定义,这样定义" i am lsj"就是在字符串常量区分配空间  
    //即不能对str进行操作,在deleteSpace中也不能通过ptr赋值了  
    //系统编译报错  
    //char *str="  i am lsj   ";   
    cout<<str<<endl; 
    deleteSpace(str); 
    cout<<str<<":The end"<<endl; 
    system("pause"); 
    return 0; 

#include<iostream>
#include<cctype>
using namespace std;

void deleteSpace(char* str)
{
 char *ptr = str;
 bool flag = true;
 while(isspace(*str++));//去除字符串开始的空格
 --str;
 while(*str){
  if(isalpha(*str)){
   if(ptr != str)//防止同一个空间赋值
    *ptr++ = *str;
   flag = true;
  }
  else{
   if(flag){
    *ptr++ = *str;
    flag = false;
   }
  }
  str++;
 }
 ptr--;//ptr已经被加1了,特别注意
 if(isspace(*ptr)) //去除结尾的空格
  *ptr = '\0';
 else
  *++ptr = '\0';
};

int main()
{
 char str[]="  i am lsj   ";
 //这里不能定义,这样定义" i am lsj"就是在字符串常量区分配空间
 //即不能对str进行操作,在deleteSpace中也不能通过ptr赋值了
 //系统编译报错
 //char *str="  i am lsj   ";
 cout<<str<<endl;
 deleteSpace(str);
 cout<<str<<":The end"<<endl;
 system("pause");
 return 0;
}

 

 

 

 

 

 

 

补充:软件开发 , Delphi ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,