indexOfString str-等于其他字符串

如何解决indexOfString str-等于其他字符串

我需要编写一种方法来检查其他字符串上的\“ String str \”,并返回str开始的索引。 听起来像是家庭作业,是一些家庭作业,但供我学习测试用... 我试过了:
public int IndexOf (String str) {

   for (i= 0;i<_st.length();i++)
   {
        if (_st.charAt(i) == str.charAt(i)) {
            i++;
            if (_st.charAt(i) == str.charAt(i)) {
                return i;
            }
        }
   }
   return -1;
 }
但我没有得到正确的回报。为什么?我走对了路还是走不近?     

解决方法

        恐怕你还不亲密。 这是您要做的: 循环处理字符串的字符(您应该在该字符上执行
indexOf
,我将其称为主字符)(您正在执行此操作) 对于每个字符,请检查您其他字符串的字符和此字符是否相同。 如果它们是(相同序列的可能的开始),请检查母版中的下一个字符是否与您的字符串匹配以进行检查(您可能希望遍历字符串的元素并逐个检查)。 如果不匹配,请继续使用主字符串中的字符 就像是:
Loop master string
for every character (using index i,lets say)
   check whether this is same as first character of the other string
   if it is
      //potential match
      loop through the characters in the child string (lets say using index j)

      match them with the consecutive characters in the master string 
      (something like master[j+i] == sub[j])

       If everything match,\'i\' is what you want
       otherwise,continue with the master,hoping you find a match
其他一些要点: 在Java中,方法名称以 约定小写字母 (这意味着编译器不会 抱怨,但是你的程序员同伴 可以)。所以ѭ3实际上应该是
indexOf
具有实例变量 (类级别变量)以
_
(如
_st
)并不是很好 实践。如果你的教授坚持 您可能没有太多选择,但是 请记住这一点)     ,        恐怕不是很近。该代码的基本作用是检查两个字符串在任何位置的相同位置是否有两个字符,如果是,则返回这些字符中第二个字符的索引。例如,如果
_str
是\“ abcdefg \”,而
str
是\“ 12cd45 \”,则您将返回3,因为它们在同一位置具有\“ cd \”,并且这是\“ d \”。至少,据我所知,它实际上在做什么。那是因为您正在使用相同的索引变量来索引两个字符串。 要重写
indexOf
,在
_st
中寻找
str
,必须扫描
_st
中的character8ѭ中的第一个字符,然后检查其余字符是否匹配;如果不是,请从您开始检查的位置向前移动一个位置,然后继续扫描。 (可以做一些优化,但这就是本质。)例如,如果您在
_st
的索引4上找到
str
的第一个字符,而
str
则是六个字符长,找到了您需要的第一个字符查看其余五个(包括
str
\的索引1-5)是否匹配
_st
\ n的索引5-10(最简单的方法是检查
str
的所有六个字符是否与
_st
的从4开始的子字符串相去)六个字符)。如果所有内容都匹配,则返回找到第一个字符的索引(在该示例中为4)。您可以在
_st.length() - str.length()
停止扫描,因为如果在此之前没有发现它,则根本不会找到它。 观点:不要在每个循环中都调用
length
函数。 JIT可能可以优化呼叫,但是如果您知道
_st
在此功能过程中不会发生变化(并且如果您不知道,则应要求这样做),将grab24ѭ转到本地然后参考。当然,由于您知道可以早于
length()
停下,所以您将使用当地人来记住可以停下的地方。     ,        对于两个相等的字符串,您都使用
i
,但您要的是第一个始终以0开头的字符串,除非找到该字符是另一个字符串。然后检查下一个字符是否相等,依此类推。 希望这可以帮助     ,        您的代码循环遍历要搜索的字符串,如果位置i上的字符匹配,它将检查下一个位置。如果字符串在下一个位置匹配,则假定字符串str包含在_st中。 您可能想做的是: 跟踪整个str是否包含在_st中。您可能可以检查所搜索的字符串的长度是否等于到目前为止匹配的字符数。 如果执行上述操作,则可以通过从i的当前值中减去到目前为止的匹配数来获得起始索引。 一个问题: 为什么不使用内置的String.IndexOf()函数?这项任务是为了让您自己实现此功能吗?     ,        也许Oracle Java API源代码确实可以帮助您:
   /**
     * Returns the index within this string of the first occurrence of the
     * specified substring. The integer returned is the smallest value
     * <i>k</i> such that:
     * <blockquote><pre>
     * this.startsWith(str,<i>k</i>)
     * </pre></blockquote>
     * is <code>true</code>.
     *
     * @param   str   any string.
     * @return  if the string argument occurs as a substring within this
     *          object,then the index of the first character of the first
     *          such substring is returned; if it does not occur as a
     *          substring,<code>-1</code> is returned.
     */
    public int indexOf(String str) {
    return indexOf(str,0);
    }

    /**
     * Returns the index within this string of the first occurrence of the
     * specified substring,starting at the specified index.  The integer
     * returned is the smallest value <tt>k</tt> for which:
     * <blockquote><pre>
     *     k &gt;= Math.min(fromIndex,this.length()) && this.startsWith(str,k)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists,then -1 is returned.
     *
     * @param   str         the substring for which to search.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index within this string of the first occurrence of the
     *          specified substring,starting at the specified index.
     */
    public int indexOf(String str,int fromIndex) {
        return indexOf(value,offset,count,str.value,str.offset,str.count,fromIndex);
    }

    /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched,and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source,int sourceOffset,int sourceCount,char[] target,int targetOffset,int targetCount,int fromIndex) {
    if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
    }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
    if (targetCount == 0) {
        return fromIndex;
    }

        char first  = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character,now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j] ==
                         target[k]; j++,k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-