题目:
开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
思路:
因为输入是字符串,要提取其中的坐标信息,考虑用正则表达式去匹配筛选,至于坐标计算都是小意思了,开干
代码实现:
using System; using System.Text.RegularExpressions; using System.Collections.Generic; public class Test { static void Main() { string[] str = Console.ReadLine().Split(';'); List<string> coordList= new List<string>(); string pattern = @"^[ASDW]\d{1,2}\b"; CoordCalculate coordCalculate = new CoordCalculate(); for(int i=0;i<str.Length;i++) { foreach (Match match in Regex.Matches(str[i], pattern)) { Console.WriteLine(match.Groups[0]); coordList.Add(match.Groups[0].ToString()); } } Console.WriteLine(coordCalculate.coordCal(coordList)); } } public class CoordCalculate { int x=0; int y=0; string coords = ""; public string coordCal(List<string> coordlist) { foreach(var coord in coordlist) { if(coord.Contains("A")) { x-=Convert.ToInt32(coord.Substring(1)); } else if(coord.Contains("S")) { y-=Convert.ToInt32(coord.Substring(1)); } else if(coord.Contains("D")) { x+=Convert.ToInt32(coord.Substring(1)); } else if(coord.Contains("W")) { y+=Convert.ToInt32(coord.Substring(1)); } } coords=x+","+y; return coords; } }