Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip substring in String.Contains in Java

Tags:

java

For a given string

String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";

How can we check if welcomeMessage contains "Welcome, you have notification" substring by escaping name variable as name variable keeps on changing?

I want to achieve

welcomeMessage.contains("Welcome, You have notification!"); //to return true

What would be the best way to skip name variable?

like image 925
MPK Avatar asked Apr 07 '26 06:04

MPK


2 Answers

String#startsWith & endsWith

The String class provides specific methods:

  • startsWith
  • endsWith

Example:

boolean containsPhrases = 
    message.startsWith( "Welcome" )
    &&
    message.endsWith( ", You have notification!" )
;
like image 174
Basil Bourque Avatar answered Apr 09 '26 20:04

Basil Bourque


very simple

String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
            System.out.println(welcomeMessage + " matches " + welcomeMessage.matches("Welcome.+You have notification!"));
like image 20
anjanb Avatar answered Apr 09 '26 22:04

anjanb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!