Home > Java > JavaBase > Java determines whether a string contains characters

Java determines whether a string contains characters

angryTom
Release: 2019-11-15 17:25:35
Original
4832 people have browsed it

Java determines whether a string contains characters

java determines whether a string contains characters

3 ways to determine whether a string contains a certain substring (Recommended tutorial: java tutorial)

1. startsWith()

This method has two variants and tests if a string starts at the specified index at the specified prefix or by default at the starting position of the string

The syntax defined for this method is as follows:

public boolean startsWith(String prefix, int toffset)
or
public boolean startsWith(String prefix)
Copy after login

prefix – The prefix to match. Here are the details of the parameters: toffset – where to start looking for the string.

The return value is true and false

import java.io.*;
 
public class Test{
   public static void main(String args[]){
      String Str = new String("Welcome to Yiibai.com");
 
      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Welcome") );
 
      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Tutorials") );
 
      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Yiibai", 11) );
   }
}
Copy after login

2. contains method

java.lang.String.contains()
Copy after login

The method returns true if and only if this string contains the specified Char value sequence

The return value is true and false

public static void main(String[] args) {
        String str = "abc";
        boolean status = str.contains("a");
        if(status){
            System.out.println("包含");
        }else{
            System.out.println("不包含");
        }
    }
Copy after login

3. IndexOf method

The purpose of java.lang.String.indexOf() is Find the position of a word in a string, and also determine whether a string contains a certain character.

The return value of indexOf is int

public static void main(String[] args) {
    String str1 = "abcdefg";
    int result1 = str1.indexOf("ab");
    if(result1 != -1){
        System.out.println("字符串str中包含子串“ab”"+result1);
    }else{
        System.out.println("字符串str中不包含子串“ab”"+result1);
    }
}
Copy after login

The above is the detailed content of Java determines whether a string contains characters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template