串的模式匹配算法之一:简单算法

本文介绍了一个使用C#实现的基本子串匹配算法示例。该算法通过比较主串与目标子串来判断子串是否存在于主串中,并给出匹配位置。此算法适合编程初学者学习并实践基本的数据结构和字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习了几天数据结构,一直有种冲动想上机试试,可惜教程是C语言版的,对于我这个对C语言不是很熟悉的初学者就有点困难,于是就用C#模拟:

 

None.gifusing System;
None.gif
namespace EasyIndex
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
class Index
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string s="acabaabcaabaabcac";
InBlock.gif            
string m="abaabcac";
InBlock.gif            
int i=0;
InBlock.gif            
int j=0;
InBlock.gif            
while(i<s.Length && j<m.Length)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(s[i]==m[j])
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    i
++;
InBlock.gif                    j
++;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    i
=i-j+2;//从主串的下一个位置开始重新匹配;
InBlock.gif
                    j=1;//子串从头开始重新匹配;
ExpandedSubBlockEnd.gif
                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
if(j>=m.Length)//说明m是s的一个子串,而且pos是i-m.Lengh+1,因为数组从0开始计数;
ExpandedSubBlockStart.gifContractedSubBlock.gif
            dot.gif{
InBlock.gif                Console.WriteLine(
"m与s中第"+Convert.ToString(i-m.Length+1)+"个元素开始的子串相匹配!");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(
"m不是s的子串!");
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/gmq/archive/2006/09/26/515577.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值