不使用的索引 [英] without using index of

查看:91
本文介绍了不使用的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个字符串是否是另一个字符串的子字符串,而不使用
指数 .我考虑过在方法中使用嵌套循环和char,但是我不知道如何使用它们.

i want to check if a string is a substring from the other string or not without using
index of . i thought of using nested loops and char at method but i dont know how to use them

推荐答案

选择一个 ^ ]

选择一个在线教程 [
Pick a string searching algorithm[^]

Pick an online tutorial[^]

You should now have enough info to solve your problem

Your attempted solution is not quite right - the issues are

1. You are using hard coded lengths, use the string.length() method instead

2. You seem to have the smallString & bigString the wrong way round in the inner comparison loop. I assume that you are searching for smallString inside bigString

3. You are not incrementing the index for the big string in the inner loop - the index should be start + j

4. The matching part of the algorithm is fatally flawed. If the first character in the small string matches then you set flag to true. If the second character doesn''t match then flag will still be true. Instead set flag to true before the inner loop and if there is a character mismatch, then set flag to false and break from the inner loop (once one character fails, there is no need to continue)

5. The output is displaying both strings, I think you probably want to display where the substring starts at as well , i.e. start

6. If the string is not found then you will get an array indexing error, the upper bound of the outer loop should be bigString.length() - smallString.length() + 1

Updated version:

public class subString
{
  static public void checkSubString(String smallString, String bigString)
  {
    int start;
    boolean flag;
    for (int i = 0; i < bigString.length() - smallString.length() + 1; i++)
    {
      start=i;
      flag=true;
      for (int j= 0; j < smallString.length(); j++)
      {
        if(bigString.charAt(start + j) != smallString.charAt(j))
        {
          flag=false;
          break;
        }
      }
      if(flag)
      {
        System.out.println("( "+smallString+" is subString of " + bigString + " from position " + start + ")");
        break;
      }
    }
  }
}


这篇关于不使用的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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