简单的子串搜索(强力) [英] Simple substring search (brute force)

查看:45
本文介绍了简单的子串搜索(强力)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用蛮力技术进行简单的子字符串搜索,但出现了我看不到的错误.我对编程很陌生,因此请记住这一点.问题可能很简单.

I'm trying to make a simple substring search using the brute force technique but I'm getting an error which I can't see. I'm quite new to programming so please keep that in mind. The problem might be very simple.

using System;
using System.Collections;
using System.Collections.Generic;

namespace SubstringSearch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter some letters: ");
            string sequence = Console.ReadLine();
            Console.Write("Enter the sequence you want to search for: ");
            string pattern = Console.ReadLine();

            Console.WriteLine(Search(pattern, pattern.Length, sequence, sequence.Length));

            Console.ReadLine();
        }

        public static int Search(string pattern, int patternLength, string sequence, int stringLength)
        {
            int i;
            int j;

            if (stringLength >= patternLength)
            {
                for (j = 0; j <= (stringLength - patternLength); j++)
                {
                    for (i = 0; i < patternLength && pattern[i] == sequence[i + j]; i++);

                    if (i >= patternLength)
                        return j;
                    else
                        return -1;
                }
            }
            else
                return -1;
        }
    }
}

所以我收到一个错误和一个警告.首先,它告诉我并非所有代码路径都返回一个值(在Search()中).我不明白为什么.其次,我得到一个警告,说我的整数"j"在第一个for循环中(在"j ++"处)不可访问.

So I'm getting one error and one warning. First it tells me that not all code paths return a value ( in Search() ). I can't see why. Second I get a warning that my integer 'j' is unreachable in the first for-loop (at 'j++').

请帮助!我敢肯定答案很简单,但我看不到.

Please help! I'm sure the answer is quite simple, but I just can't see it.

推荐答案

问题似乎出在您的第二个for循环中.试试这个:

The issue seems to lie in your second for loop. Try this:

 if (stringLength >= patternLength)
        {
            for (j = 0; j <= (stringLength - patternLength); j++)
            {
                for (i = 0; i < patternLength && pattern[i] == sequence[i + j]; i++)
                {
                    if (i >= patternLength)
                        return j;                       
                }
            }
        }
 return -1;

那应该删除所有警告和错误并进行编译.为什么不使用 .Contains() 方法?

That should remove all warnings and errors and compile. Why are you not using the .Contains() method?

包含

如果value参数出现在此字符串中,或​​者如果值是空字符串(");否则为假.

True if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.

这篇关于简单的子串搜索(强力)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆