【问题标题】:Find substring within a string [duplicate]在字符串中查找子字符串[重复]
【发布时间】:2014-05-09 20:07:35
【问题描述】:

我编写了一个代码来在 java 中的字符串中查找子字符串,但我想知道是否有一种简短的方法可以做到这一点,或者是否有一个内置函数可以做到这一点。

代码如下:

import java.util.*;
class substr 
{
    public static void main (String args [])
    {
        String str1 = new String();
        String str2 = new String();
        String str3 = new String();
        int check=1,k;
        Scanner obj= new Scanner (System.in);
        System.out.println("Enter a string");
        str1=obj.nextLine();
        System.out.println("Enter Sub String");
        str2=obj.nextLine();
        int len=str1.length();
        System.out.println(check);
        for( int c = 0 ; c < len&&check!=0 ; c++ )
        {
            for( int i = 1 ; i <= len - c&& check!=0 ; i++ )
            {
                str3 = str1.substring(c, c+i);
                if (str2.equals(str3))
                {   
                    check=0;
                }
            }
       }
       System.out.println(check);
       if (check==0)
       {
           System.out.println("Sub String");
       }
       else if ( check==1)
       {
           System.out.println("No");
       }
    }
}

【问题讨论】:

  • 不清楚你在问什么。您实际上已经使用了 substring 方法。那么问题出在哪里?
  • @donfuxx 我只是想减少我的位置(代码行)并找到其他方法来做到这一点

标签: java string substring


【解决方案1】:

如果您正在寻求一种方法来执行您的代码所做的事情(检查一个字符串是否是另一个字符串的子字符串),您可以使用String#contains:

if(str1.contains(str2)) {
    System.out.println("Sub String");
} else {
    System.out.println("No");
}


您也可以使用String#indexOf
if(str1.indexOf(str2)>=0) {
    System.out.println("Sub String");
} else {
    System.out.println("No");
}

【讨论】:

  • 感谢您的帮助。
  • @user3478298 不客气
猜你喜欢
  • 2020-02-24
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2017-10-23
  • 2011-07-13
相关资源
最近更新 更多