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();
}
}
}
作者:Czhenya
链接:https://czhenya.blog.csdn.net/article/details/78070440
来源:CSDN
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。