java - 查找字符串 2 在字符串 1 中开始的索引

标签 java string

所以我正在编写一个具有多种不同方法的程序,其中一个方法要求查找第二个字符串在第一个字符串中开始的索引

该方法接受两个字符串作为参数,并返回第二个字符串在第一个字符串中开始的位置的字符索引。例如:

IN:乐高积木,出发

输出:2

此方法的要点是我只能使用 String 中的 charAtsubstringlength类,并且没有其他类方法

我目前没有代码,我需要了解如何启动它

编辑:感谢您的帮助,现在我不想查找第二个字符串开始的索引,而是想找到第二个字符串在第一个字符串的最右侧区域开始的索引。例如

IN:密西西比州,SS 输出:5

提前致谢

最佳答案

public int indexOf(final String source, final String find) {
    // loop from first character to last character that still leaves length of 'find' string available
    for(int sourcePos = 0; sourcePos < source.length() - find.length(); sourcePos++) {
        boolean found = true;
        for(int findPos = 0; findPos < find.length(); findPos++) {
            // if the current char is not a match, then mark as not found and break from loop
            if(source.charAt(sourcePos) != find.charAt(findPos)) {
                found = false;
                break;
            }
        }
        if(found) {
            return sourcePos;
        }
    }

    // return -1 to indicate the string was not found
    return -1;
}

关于java - 查找字符串 2 在字符串 1 中开始的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708394/

相关文章:

java - 阿基利安 : Transaction is required to perform this operation

python - 将整数转换为其 ascii 值的字符串

c++ - C++ char到int转换为大于9的数字

java - Java中如何修改这个String?

c# - 统计一个字符在字符串中改变了多少次

java - 如何以编程方式制作可绘制形状 (Android)

java - 在 JBOSS for DB2 中创建数据源

java - 将 Swift iOS 客户端连接到 Netty 服务器

Javascript 迭代 Json 数组获取值

java -/* 和/** 用于 javadoc - 只是 Eclipse 还是这是 Java 约定?