目录
7.字符串去特定字符
首先,是程序末尾要加上一个getchar(),是因为scanf函数在输入时遇到回车即结束,而回车会保存在系统的内存里,这样接下来的一组数据使用scanf时会率先将回车输入,就会造成问题。
这个问题我现在也不太理解,等之后再进一步弄懂
其次,如果要输入字符串,最好用fgets,因为有可能包含空格,scanf没用
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
int main(){
char martix[1000];
char c;
while(fgets(martix,100,stdin)){
scanf("%c",&c);
int len = strlen(martix);
int choose[1000]={0};
for(int i=0;i<len;i++){
if(martix[i]!=c){
printf("%c",martix[i]);
}
}
memset(martix,'\0',sizeof(martix));
getchar();
}
return 0;
}
8.数组逆置
前面是我的,后面是一位大神的
这一题算是让我搞清楚一点输入是什么一回事了,回车键只是会让scanf暂停,而fgets会连回车一起包进来,这时候如果逆序输入,会一起把回车键输出
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
int main(){
char martix[202];
while(fgets(martix,201,stdin)){
for(int i=strlen(martix)-2;i>=0;i--){
printf("%c",martix[i]);
}
printf("\n");
memset(martix,'\0',sizeof(martix));
}
return 0;
}
#include <cstdio>
#include <cstring>
int main()
{
char str[210];
while(gets(str))
{
int len=strlen(str);
for(int i=0;i<len/2;++i)
{
char temp=str[i];
str[i]=str[len-1-i];
str[len-1-i]=temp;
}
printf("%s\n",str);
}
return 0;
}
9.比较字符串
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
int main(){
int m;
while(scanf("%d",&m)!=EOF){
char martix[2][52];
while(m--){
scanf("%s %s",&martix[0],&martix[1]);
if(strlen(martix[0])>strlen(martix[1])){
printf("%s is longer than %s\n",martix[0],martix[1]);
}else if(strlen(martix[0])<strlen(martix[1])){
printf("%s is shorter than %s\n",martix[0],martix[1]);
}else{
printf("%s is equal long to %s\n",martix[0],martix[1]);
}
memset(martix[0],'\0',sizeof(martix[0]));
memset(martix[1],'\0',sizeof(martix[1]));
}
}
return 0;
}
10.编排字符串
这一题我测试了很多种情况都是对的,但不知道为什么codeup无法通过
#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
int main(){
int m;
char martix[101][30];
while(scanf("%d",&m)!=EOF){
getchar();
for(int i=0;i<m;i++){
fgets(martix[i],30,stdin);
int len = strlen(martix[i]);
martix[i][len-1] = '\0';
if(i==0){
printf("1=%s\n",martix[i]);
}else if(i==1){
printf("1=%s 2=%s\n",martix[1],martix[0]);
}else if(i==2){
printf("1=%s 2=%s 3=%s\n",martix[2],martix[1],martix[0]);
}else{
printf("1=%s 2=%s 3=%s 4=%s\n",martix[i],martix[i-1],martix[i-2],martix[i-3]);
}
}
for(int i=0;i<m;i++){
memset(martix[i],'\0',sizeof(martix[0]));
}
}
return 0;
}
#include <cstdio>
#include <cstring>
int main()
{
char a[110][40];
int n;
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
for(int j=i;i-j+1<=4&&j>=0;j--)
{
printf("%d=%s",i-j+1,a[j]);
if(j!=0)
printf(" ");
}
printf("\n");
}
}
return 0;
}