字符串2
一串数字,每两位一组,不够补0,加上32,放到新的字符串里,比如123456,12+32=44,34+32=66,56+32=88
#includeusing namespace std; char str[101]={'\0'}; char res[101]={'\0'}; int main(){ scanf("%s",&str); int len=strlen(str); if(len%2!=0){ str[len++]='0'; } int reslen=0; for(int i=0;i 2){ char temp[3]={'\0'}; temp[0]=str[i]; temp[1]=str[i+1]; int num=atoi(temp); num+=32; sprintf(res+reslen,"%d",num); char temp1[100]={'\0'}; itoa(num,temp1,10); reslen+=strlen(temp1); } cout< endl; //test(); return 0; }
总结一下字符串和整数的相互转化
//char *str
//字符串转整数 int atoi ( const char * str ); double atof ( const char * str ); long int atol ( const char * str ); int sscanf ( const char * str, const char * format, ...); int a;float b;long c; sscanf ("32,3.1415,567283","%d,%f,%d",&a,&b,&c);
//整数转字符串 char * itoa ( int value, char * str, int base ); itoa(num,temp1,10); int sprintf ( char * str, const char * format, ... ); char a[10],b[10],c[10]; sprintf(a, "%d", 32); sprintf(b, "%f", 3.1415); sprintf(c, "%d", 567283);
输入字符串,共三问,去除前面的空格,中间多个空格只保留一个空格,数字字母中间
加上_
#includeusing namespace std; int main(){ string str,res; getline(cin,str); bool start=false; int i=0,len=0; while(!start){//处理开头的空格 if(str[i]!=' '){ break; } i++; } bool fig=false,letter=false,spa=false; while(i<str.size()){ if(str[i]!=' '){ spa=false; if(str[i]>='1'&&str[i]<='9'){ if(letter){ res+='_'; letter=false; } fig=true; } else{ if(fig){ res+='_'; fig=false; } letter=true; } res+=str[i]; } else{ if(!spa){ res+=str[i]; spa=true; fig=false; letter=false; } } i++; } cout< endl; return 0; }
3.无冗余的输入一个字符串
1)输出该字符串
2)对于不是首次出现的字符,对其进行过滤,例如 abcdacdef,过滤后为 abcdef
3)对于字符 0-9,A-F,a-f,将其对应的 ASCII码的低 4位进行对调,例如将 1011,转
换为 1101,并将对应的 ACSII码对应的字符输出,若为字母,转换为大写。
#includeusing namespace std; bool flag[128]={false}; int main(){ string str,res; cin>>str; cout< endl; for(int i=0;i ){ int idx=str[i]; //cout<<"idx:"< if(!flag[idx]){ flag[idx]=true; char c=str[i]; if((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')){ int temp=idx%8; idx/=8; idx*=8;//末4位取0 int bit[4]; for(int j=0;j<4;j++){ bit[j]=temp&1; //cout< temp>>=1; } //cout<<"ge"; temp=bit[0]; bit[0]=bit[3]; bit[3]=temp; temp=bit[1]; bit[1]=bit[2]; bit[2]=temp; temp=0; for(int j=3;j>=0;j--){ //cout< temp|=bit[j]; if(j!=0) temp<<=1;//注意这里比循环次数要少做一次! } idx|=temp; c=idx; if(c>='a'&&c<='f'){ c-=32; } } res+=c; } } cout< return 0; }endl;