状态机--C#代码实现

xiaoxiao2021-02-28  6

FSM经典案例:


消除多余空格,两种状态,,, 例如:(这里的“空”表示空格的意思) 输入是:abc空空空cde空空eff 输出为:abc空cde空eff

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 状态机 { class Program { static void Main(string[] args) { string s = Console.ReadLine(); int n = 1 ; for (int i = 0; i < s.Length-1; i++) { switch (n) { case 1: if(s[i] != ' ') { Console.Write(s[i]); } else { n = 2; Console.Write(" "); } break; case 2: if (s[i] != ' ') { n = 1; Console.Write(s[i]); } else { //不输出 Console.Write(""); } break; default: Console.WriteLine("wrong state"); break; } } Console.ReadLine(); } } }

三种状态:消除多余空格使其剩余一个,,“”双引号里面正常输出,不做改变,,, 例如:(这里的“空”表示空格的意思) 输入是:abc空空空“cde 空空 eff”空空空空asd 输出为:abc空“cde 空空 eff”空asd


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 状态机_1 { class Program { static void Main(string[] args) { //Console.Write("\" \'"); string s = Console.ReadLine(); int n = 0; for (int i = 0; i < s.Length; i++) { switch(n) { case 0: if(s[i] == ' ') { n = 1; Console.Write(s[i]); } else if(s[i] == '"') { n = 2; Console.Write(s[i]); } else { n = 0; Console.Write(s[i]); } break; case 1: if (s[i] == ' ') { n = 1; } else if(s[i] == '"') { n = 2; Console.Write(s[i]); } else { n = 0; Console.Write(s[i]); } break; case 2: if(s[i] == '"') { n = 0; Console.Write(s[i]); } else { Console.Write(s[i]); } break; default: Console.WriteLine("Wrong"); break; } } Console.ReadLine(); } } } 妳是我改卟了的bug 认证博客专家 Unity C# Lua 游戏开发 一个从事游戏开发行业的U3D程序猿,本博客专注分享学到的知识和开发中遇到的问题;若有不足,敬请指正,共同学习,一起进步!!!
转载请注明原文地址: https://www.6miu.com/read-1100105.html

最新回复(0)