华为机试题:坐标移动

题目描述:
开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

输入描述:

一行字符串

输出描述:

输出输入字符串中含有该字符的个数。

输入例子:

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出例子:

10,-10

本题关键之处在于对数据的输入以及如何读取有效的字符

#include<iostream>
#include<string>
#include<cstddef>   //std::size_t
using namespace std;

int main()
{
    string str;
    while(cin>>str){
        pair<int,int> point(0,0);               //point.first point.second
        size_t found = str.find_first_of(';');  //找到第一个';'的位置
        int start = 0;

        while(found!=string::npos){
            string s1 = str.substr(start,found-start);
            start = found+1;
            found = str.find_first_of(';',found+1);

            if(s1.size()>1 && s1.size()<=3){    //合法的字符个数:2或3
                char c = s1[0];
                int n = 0;
                int invalid = 0;    //是否是正确的字符
                for(int i=1; i<s1.size(); ++i){ 
                    if(s1[i]>='0'&&s1[i]<='9')  // 提取数字
                        n = n*10 + (s1[i]-'0'); 
                    else{
                        invalid=1;
                        break;
                    }
                }
                if(invalid==0){
                    switch(c)
                    {
                        case 'A': {point.first-=n;break;}
                        case 'D': {point.first+=n;break;}
                        case 'W': {point.second+=n;break;}
                        case 'S': {point.second-=n;break;}
                    }
                }

            }
        }
        cout << point.first << ',' << point.second <<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值