HDU2054 A == B ?(字符串)

Problem Description

Give you two numbers A and B, if A is equal to B, you should print "YES", or print "NO".

Input

each test case contains two numbers A and B.

Output

for each case, if A is equal to B, you should print "YES", or print "NO".

Sample Input

1 2 2 2 3 3 4 3

Sample Output

NO YES YES NO

代码如下:

解法一(AC):

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
void is_equal(string &a){
    int len=a.length();
    if(a.find('.',0)!=string::npos){
        for(int i=len-1;a[i]=='0';i--)
        len--;
        a=a.substr(0,len);
    }
    if(a[len-1]=='.') 
    a=a.substr(0,len-1);    
}
int main(){
    string str1,str2;
    while(cin>>str1>>str2){
        is_equal(str1);
        is_equal(str2);
        if(str1==str2) printf("YES
");
        else printf("NO
");
    }
    return 0;
}

可以用这题来熟悉一下string类型的操作:

find()方法:查找字符串中是否含有某一字符。也有一个重载方法可以用来查找字符串。如果找不到不是返回-1,而是返回一个static成员-------string::npos;
substr()方法:顾名思义,就是用来截取子串的。
substring(i);会从下标为i的位置截取到末尾,注意下标从0算起。
substring(a,b);会从下标为a的位置截取,b是要截取的长度。貌似大多数语言里面截取子串都是这样的。并不是使用首末位置的下标。
比如:
s=“12345”;
s.substring(3);//那么返回值是“45”
s.substring(0,3);//那么返回值是“123”
注意截取子串操作对于原字符串不会产生影响!

解法二(AC):

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
char chr1[100015],chr2[100015];   //①
void is_equal(char a[]){    //②
    int len=strlen(a);
    int p=0;  //这一步不要写在①和②之间,会WA
    for(int i=0;i<len;i++){
        if(a[i]=='.')
        {
            p=1;
            break;
        }
    }
    if(p){
        for(int i=len-1;i>=0;i--){
            if(a[i]=='0')
               a[i]='';
            else break;
            len--;
        }
        if(a[len-1]=='.') {
            a[len-1]='';
            len--;
        }
    }
}
int main(){
  while(scanf("%s%s",chr1,chr2)!=EOF){
      is_equal(chr1);
      is_equal(chr2);
      if(strcmp(chr1,chr2)==0) printf("YES
");
      else printf("NO
");
  }    
  return 0;
}
天晴了,起飞吧
原文地址:https://www.cnblogs.com/jianqiao123/p/11364461.html