HJ17 坐标移动 C/C++

题目连接

主要思路

1.首先按分号‘;’,将输入的字符串格式化成每一个子串,然后我们处理每一个子串,分割方法为:设置一个子串变量sub_str,初始为空串,然后循环遍历主串str每一个字符,如果不是分号,则将其加到子串末尾sub_str+=str[i],如果遇到分号,则说明已经截取到了一条子串坐标,同时将子串sub_str置空,重复上述操作,最后可以截取到输入的每一条方向坐标。
2.处理刚才输入的坐标,这里主要就是分类讨论了,合法的坐标一定是长度为2或者3,第一个字符是ASWD中的一个,同时要求第二位或者第三位是数字,最后取出合法的坐标,详见代码。
3.最后就是对合法的坐标进行运算了。
具体细节见代码。关键的步骤就是按分号(;)分割子串,然后分类的时候考虑全面,后面就迎刃而解了。

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <cctype>

using namespace std;

int x,y;

void mov(char dir,int step) {
    switch (dir) {
        case 'A':x-=step;break;
        case 'S':y-=step;break;
        case 'D':x+=step;break;
        case 'W':y+=step;break;
    }
}

void sol(const string& str) {
    if(str.empty()||str.size()>3||str.size()<2)return ;
    int len = str.size();
    if(str[0]!='A'&&str[0]!='S'&&str[0]!='D'
               &&str[0]!='W')return ;
    int step = 0;
    char ch;
    if(len==2&&str[1]>'0'&&str[1]<='9') {//形如A8的坐标
        step = str[1]-'0';//步数
        ch = str[0];//方向
        mov(ch, step);
    }else if(len==3&&isdigit(str[1])&&isdigit(str[2])) {//形如A10的坐标
        step = (str[1]-'0')*10+(str[2]-'0');
        ch = str[0];
        mov(ch,step);
    }
}

int main() {
    string str;
    cin>>str;
    string sub_str = "";
    //格式化分割字符串,将处理好的子串传入函数进行处理
    for(int i = 0;i<str.size();++i) {
        if(str[i]==';') {
            sol(sub_str);
            sub_str = "";
            continue;
        }
        else {
            sub_str+=str[i];
        }
    }
    cout<<x<<','<<y<<endl;
    
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值