Reputation: 24871
I get a string which I have to check if it ends with SUCCESS
. The string I get is multi-line, that is, it has \n
in it. If it ends with SUCCESS.
, I have to return true
, and if it ends with FAILED.
, I have to return false
. However
pValidationReport.endsWith("SUCCESS.")
evaluates to false
even when the pValidationReport
ends with FAILED.
as can be seen below:
The method is as follows:
private boolean isValidationSuccess(String pValidationReport)
{
if(pValidationReport.endsWith("SUCCESS."))
return true;
else if(pValidationReport.endsWith("FAILED."))
return false;
}
What I am missing?
Upvotes: 2
Views: 116
Reputation: 1011
first trim the string then chcek for endsWith()
pValidationReport.trim().endsWith("SUCCESS.")
The Java String Trim method is an instance method that is use to remove extra spaces from the start and end of a string. The String Trim method is used on the string object or literal. In Java, Strings are immutable, so once they are created, the content cannot be modified. Due to this reason, the result will be a newly created string object with no spaces at both ends of a string. it is evident that after trimming the string, it returns a new string object. When there is no space to trim at both sides, the same object of type String will be returned instead of a new one.
This endsWith() method returns a true if the character sequence represented by the argument is a suffix of the character sequence represented by this object, else false.
Upvotes: 2
Reputation: 165
If your input string has whitespace characters after the substring you're seeking for, it won't match. You could possibly use the regex for the purpose:
private boolean isValidationSuccess(String pValidationReport)
{
Pattern successPattern = Pattern.compile(".*SUCCESS\\.\\s*$");
return successPattern.matcher(pValidationReport).matches();
}
The \s* ensures that the SUCCESS. string at the end will be recognized even if followed by any arbitrary number of spaces, tabs, newlines, carriage-returns, form-feeds and vertical-tabs. It is also possible to move the Pattern to a final instance variable and then just use the matcher in your method, saving the call to compile():
private final Pattern successPattern = Pattern.compile(".*SUCCESS\\.\\s*$");
private boolean isValidationSuccess(String pValidationReport)
{
return this.successPattern.matcher(pValidationReport).matches();
}
Upvotes: 1