How to check if a string contains a substring in java
Use the contains() method to check whether a string contains a substring. This method is case-sensitive and returns true or false. If you need to ignore case, you can convert the case uniformly before comparing. If you need to obtain the position of the substring, use the indexOf() method to find the return index, otherwise -1 will be returned. For complex pattern matching, it is recommended to use Pattern and Matcher for regular matching.
To check if a string contains a substring in Java, you can use the contains() method. This is the most straightforward and commonly used approach.
Using contains() method
The contains() method returns true if the specified sequence of characters is present in the string, otherwise it returns false .
It is case-sensitive, so make sure the case matches unless you handle it explicitly.
Example:
String str = "Hello, welcome to Java";boolean found = str.contains("welcome");
System.out.println(found); // Output: true
Case-insensitive search
If you need a case-insensitive check, convert both strings to lowercase (or uppercase) before using contains() .
Example:
String str = "Hello, welcome to Java";boolean found = str.toLowerCase().contains("WELCOME".toLowerCase());
System.out.println(found); // Output: true
Using indexOf() method
Another way is using indexOf() . It returns the starting index of the substring if found, or -1 if not.
This method is useful when you also need the position of the substring.
Example:
String str = "Hello, welcome to Java";int index = str.indexOf("welcome");
if (index != -1) {
System.out.println("Found at index: " index);
}
Using regular expressions (Pattern and Matcher)
For more complex pattern matching, you can use java.util.regex.Pattern and Matcher .
This is helpful when dealing with dynamic patterns or partial matches beyond simple substrings.
Example:
import java.util.regex.*;String str = "Hello, welcome to Java";
Pattern pattern = Pattern.compile("welcome");
Matcher matcher = pattern.matcher(str);
boolean found = matcher.find();
System.out.println(found); // Output: true
Basically just pick contains() for simple cases. Use indexOf() if you need location info, and regex for advanced pattern checks.
The above is the detailed content of How to check if a string contains a substring in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

First, enable the built-in scaling function of UC browser, go to Settings → Browse Settings → Font and Typesetting or Page Scaling, and select a preset ratio or custom percentage; second, you can force the page display size by opening or pinching gestures with two fingers; for web pages that restrict scaling, you can request the desktop version of the website to unlock the restrictions; advanced users can also modify the viewport attributes by executing JavaScript code in the address bar to achieve a more flexible forced scaling effect.

Real-time systems require deterministic responses, because correctness depends on the result delivery time; hard real-time systems require strict deadlines, missed will lead to disasters, while soft real-time allows occasional delays; non-deterministic factors such as scheduling, interrupts, caches, memory management, etc. affect timing; the construction plan includes the selection of RTOS, WCET analysis, resource management, hardware optimization and rigorous testing.

The answer is to use Thread.currentThread().getStackTrace() to get the call method name, and obtain the someMethod name of the call anotherMethod through index 2. Since index 0 is getStackTrace, 1 is the current method, and 2 is the caller, the example output is "Calledbymethod:someMethod", which can also be implemented by Throwable, but attention should be paid to performance, obfuscation, security and inline impact.

Java exception handling catches exceptions through try-catch blocks, finally blocks ensure resource cleanup, try-with-resources automatically manage resources, throws declare exceptions, custom exceptions to deal with specific errors, and follows best practices such as catching specific exceptions, not ignoring exceptions, and avoiding empty catch blocks, thereby achieving robust and maintainable code.

The Optional class is used to safely handle values that may be null, avoiding null pointer exceptions. 1. Create an instance using Optional.ofNullable to handle null values. 2. Check and access values through isPresent or ifPresent security to avoid direct call to get to cause exceptions. 3. Use orElse and orElseGet to provide default values, or use orElseThrow to throw a custom exception. 4. Convert or filter values through map and filter chain operations to improve code readability and robustness.

Edge occupies a high CPU because of the high consumption of resources based on Chromium kernel, plus factors such as multi-tab pages, plug-in running, website scripts and rendering mechanisms; solutions include: 1. Close unnecessary extensions to reduce the burden on the background; 2. Enable the "Sleep Tag" function to reduce the use of idle tag resources; 3. Clean up the background process and close GPU rendering related settings; 4. Update the browser and system to ensure compatibility and performance optimization.

Use std::transform combined with ::toupper to convert the string to uppercase, such as std::transform(str.begin(), str.end(), str.begin(),::toupper). This method is suitable for ASCII characters. Modify the original string. If you need to keep the original string, you can copy it first. It is recommended to use the ICU library in Unicode scenarios.

Use the getClass() method to get the runtime class of the object, such as str.getClass() to return the Class object; for types, you can directly use the String.class syntax. The Class class provides methods such as getName(), getSimpleName() to obtain class information, such as num.getClass().getSimpleName() to output Integer.
