📜  在Java中搜索字符串中的字符和子字符串

📅  最后修改于: 2022-05-13 01:54:57.092000             🧑  作者: Mango

在Java中搜索字符串中的字符和子字符串

从编程的角度来看,字符串是一个非常重要的方面,因为许多问题都可以在字符串之间进行框定。出现了各种各样的概念和问题,这些概念和问题对于理解字符串至关重要。现在在这里将讨论使用字符串的不同方法,我们将使用字符串和子字符串来处理字符,这些字符是输入字符串的一部分,借助内置方法,并提出逻辑列出各种不同的方法,如下所示:

在字符串中搜索字符

方式一: indexOf(char c)

它搜索给定字符串中指定字符的索引。它从字符串的开头到结尾(从左到右)开始搜索,如果找到则返回相应的索引,否则返回-1。

句法:

int indexOf(char c)
// Accepts character as argument, Returns index of 
// the first occurrence of specified character 

方式2: lastIndexOf(char c)

它从字符串的末尾开始向后搜索,并在遇到时返回指定字符的索引。

句法:

public int lastIndexOf(char c)
// Accepts character as argument, Returns an 
// index of the last occurrence specified 
// character

方式3: IndexOf(char c, int indexFrom)

它从字符串中的指定索引开始向前搜索,遇到指定字符时返回对应的索引,否则返回-1。

句法:

public int IndexOf(char c, int indexFrom)

参数:

  • 要搜索的字符
  • 一个整数从哪里搜索

返回类型:在转发方向上出现在指定索引处或之后的指定字符的索引。

方式4:lastIndexOf(char c, int fromIndex)

它从字符串中的指定索引开始向后搜索。并在遇到指定字符时返回对应的索引,否则返回-1。

句法:

public int lastIndexOf(char c, int fromIndex)

方式6:charAt(int indexNumber)

返回给定字符串中指定索引处存在的字符indexNumber 。如果字符串中不存在指定的索引号,则该方法将引发未经检查的异常 StringIndexOutOfBoundsException。

句法:

char charAt(int indexNumber)

例子:

Java
// Java Program to Illustrate to Find a Character
// in the String
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // String in which a character to be searched.
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Returns index of first occurrence of character.
        int firstIndex = str.indexOf('s');
        System.out.println("First occurrence of char 's'"
                           + " is found at : "
                           + firstIndex);
  
        // Returns index of last occurrence specified
        // character.
        int lastIndex = str.lastIndexOf('s');
        System.out.println("Last occurrence of char 's' is"
                           + " found at : " + lastIndex);
  
        // Index of the first occurrence of specified char
        // after the specified index if found.
        int first_in = str.indexOf('s', 10);
        System.out.println("First occurrence of char 's'"
                           + " after index 10 : "
                           + first_in);
  
        int last_in = str.lastIndexOf('s', 20);
        System.out.println("Last occurrence of char 's'"
                           + " after index 20 is : "
                           + last_in);
  
        // gives ASCII value of character at location 20
        int char_at = str.charAt(20);
        System.out.println("Character at location 20: "
                           + char_at);
  
        // Note: If we uncomment it will throw
        // StringIndexOutOfBoundsException
        // char_at = str.charAt(50);
    }
}


Java
// Java Program to illustrate to Find a Substring
// in the String
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // A string in which a substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Returns index of first occurrence of substring
        int firstIndex = str.indexOf("Geeks");
  
        System.out.println("First occurrence of char Geeks"
                           + " is found at : "
                           + firstIndex);
  
        // Returns index of last occurrence
        int lastIndex = str.lastIndexOf("Geeks");
        System.out.println(
            "Last occurrence of char Geeks is"
            + " found at : " + lastIndex);
  
        // Index of the first occurrence
        // after the specified index if found
        int first_in = str.indexOf("Geeks", 10);
        System.out.println("First occurrence of char Geeks"
                           + " after index 10 : "
                           + first_in);
  
        int last_in = str.lastIndexOf("Geeks", 20);
        System.out.println("Last occurrence of char Geeks "
                           + "after index 20 is : "
                           + last_in);
    }
}


Java
// Java Program to Illustrate How to Find a Substring
// in the String using contains() Method
  
// Importing required classes
import java.io.*;
import java.lang.*;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // String in which substring
        // to be searched
        String test = "software";
  
        CharSequence seq = "soft";
        boolean bool = test.contains(seq);
        System.out.println("Found soft?: " + bool);
  
        // Returns true substring if found.
        boolean seqFound = test.contains("war");
        System.out.println("Found war? " + seqFound);
  
        // Returns true substring if found
        // otherwise return false
        boolean sqFound = test.contains("wr");
        System.out.println("Found wr?: " + sqFound);
    }
}


Java
// Java Program to Match ofstart and endof a Substring
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Input string in which substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Print and display commands
        System.out.println(str.startsWith("Geek"));
        System.out.println(str.startsWith("is", 14));
        System.out.println(str.endsWith("port"));
    }
}


输出
First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

方式七:在字符串中查找子字符串

上面提到的在字符串中查找字符的方法也可以用于在字符串中查找子字符串。

例子

Java

// Java Program to illustrate to Find a Substring
// in the String
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // A string in which a substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Returns index of first occurrence of substring
        int firstIndex = str.indexOf("Geeks");
  
        System.out.println("First occurrence of char Geeks"
                           + " is found at : "
                           + firstIndex);
  
        // Returns index of last occurrence
        int lastIndex = str.lastIndexOf("Geeks");
        System.out.println(
            "Last occurrence of char Geeks is"
            + " found at : " + lastIndex);
  
        // Index of the first occurrence
        // after the specified index if found
        int first_in = str.indexOf("Geeks", 10);
        System.out.println("First occurrence of char Geeks"
                           + " after index 10 : "
                           + first_in);
  
        int last_in = str.lastIndexOf("Geeks", 20);
        System.out.println("Last occurrence of char Geeks "
                           + "after index 20 is : "
                           + last_in);
    }
}
输出
First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8

方式8: contains(CharSequence seq):如果字符串包含指定的char值序列,则返回true,否则返回false。它的参数指定要搜索的字符序列,如果 seq 为 null,则抛出 NullPointer 异常。

句法:

public boolean contains(CharSequence seq)

例子

Java

// Java Program to Illustrate How to Find a Substring
// in the String using contains() Method
  
// Importing required classes
import java.io.*;
import java.lang.*;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // String in which substring
        // to be searched
        String test = "software";
  
        CharSequence seq = "soft";
        boolean bool = test.contains(seq);
        System.out.println("Found soft?: " + bool);
  
        // Returns true substring if found.
        boolean seqFound = test.contains("war");
        System.out.println("Found war? " + seqFound);
  
        // Returns true substring if found
        // otherwise return false
        boolean sqFound = test.contains("wr");
        System.out.println("Found wr?: " + sqFound);
    }
}
输出
Found soft?: true
Found war? true
Found wr?: false

方式9:匹配字符串开始和结束

  • boolean startsWith(String str):如果字符串str 存在于给定字符串的开头,则返回 true,否则返回 false。
  • boolean startsWith(String str, int indexNum):如果字符串str 存在于给定字符串中索引 indexNum 的开头,则返回 true,否则返回 false。
  • boolean endsWith(String str):如果字符串str 存在于给定字符串的结尾,则返回 true,否则返回 false。

例子:

Java

// Java Program to Match ofstart and endof a Substring
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Input string in which substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Print and display commands
        System.out.println(str.startsWith("Geek"));
        System.out.println(str.startsWith("is", 14));
        System.out.println(str.endsWith("port"));
    }
}
输出
true
true
false