28.找出字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.wereash.scut_hot100;
import java.util.Scanner;
public class Solution028 { public static void main(String[] args){ Scanner scanner=new Scanner(System.in); String haystack=scanner.nextLine(); String needle=scanner.nextLine(); int left=0,right=needle.length(); while(left<=haystack.length()-right){ if(needle.equals(haystack.substring(left,left+right))){ System.out.println("字符串起点为:"+left); return; } left++; } System.out.println(needle+"不是"+haystack+"的子串"); } }
|