两个小时四道编程题,只做出来一道题,而且用了1个小时20分钟才AC。
第一题实际上不是特别难,字符串转换问题。比如一个字符串“Hello World”,转换成“wORLD hELLO”,大小写要反转。其实思路比较简单,就是通过空格切分,每一个单词一个单词逆转。由于用C++写,指针控制不好很容易出错,开始又不知道是哪里的指针溢出出错。所以调试浪费了时间。
#include<iostream>
#include<string>
#include<ctype.h>
using namespace std;
string trans(string s, int n) {
// write code here
string s2 = s;
int i = 0,j= n-1,q = 0;
int tmp;
i = j;
while(j>=0&&i>=0){
cout<<"i ="<<i<<"j= "<<j<<endl;
while(i>=0&&s[i]!=' '){//字符串开头的判断i不能小于0,否则访问字符串出错。采用&&的骤死式特点。
i--;
}
tmp = i+1;
while(tmp<=j){
if(s[tmp]>='a'&&s[tmp]<='z'){
char c = toupper(s[tmp]);
//cout<<"s[tmp] ="<<s[tmp]<<"c="<<c<<endl;
s2[q] = c;
//cout<<"q ="<<q<<"s2[q]="<<s2[q]<<endl;
tmp++;
q++;
}else if(s[tmp]>='A'&&s[tmp]<='Z'){
char c = tolower(s[tmp]);
//cout<<"s[tmp] ="<<s[tmp]<<"c="<<c<<endl;
s2[q] = c;
//cout<<"q ="<<q<<"s2[q]="<<s2[q]<<endl;
tmp++;
q++;
}
}
if(i>=0&&s[i]== ' '){//当i小于0时就不用继续复制了,所以用&& 骤死式的特点。
s2[q++] = s[i--];
}
j = i;
}
return s2;
}
int main(){
string s1 = "this is A sample";
string s2 =trans(s1,16);
cout<<s2<<endl;
system("pause");
}
总结:
(1)&& 和|| 是骤死式的,因此优先判断的条件写在&&的前面。
(2)判断字符c的大小写、是否为字母、数字:
是否为字母:isapha(c),是返回1
是否为数字: isdigit(c),是返回1
判断大小写:islower(c) isupper(c)
大小写转换:tolower(c) toupper(c)
——头文件 ctype.h
以上其实也可以直接判断
是否为字母:if(c>=’a’&&c<=’z’||c>=’A’&&c<=’Z’)
是否为数字:if(c>=’0’&&c<=’9’)(c is a char)
判断大小写:if(c>=’a’&&c<=’z’)- islower() if(c>=’A’&&c<=’Z’)–isupper()
大小写转换:c = c+32 –tolower(c) c = c-32 –toupper(c)
(3) ascii码值
0-9: 48~57
a-z:97~122
A-Z: 65~90( 小写比大写多32)