Part-1: http://newdelhipowershellusergroup.blogspot.com/2012/01/part-1-text-manipulation-in-powershell.html | using Trim(),TrimEnd(),TrimStart()
Part-2: http://newdelhipowershellusergroup.blogspot.com/2012/01/part-2-text-manipulation-in-powershell.html | ToUpper(),ToLower()
Hi,
Today we are going to use .StartsWith() and .EndsWith() methods to play with our text.
we are using the same text which we used in previous posts and saving the text in a variable $text
$text = "The Quick brown fox jumps over the lazy dog"
Lets start.
.StartsWith()
This test that check that the string start with the character which we specified in .StartWith() and it give result is Boolean, the result is either “True” or “false”
lets check if our text start with “The Quick”
the result is “True” , which means yes our text is start with “The Quick”
NOTE: By default the the text which we specified in StartsWith() and EndsWith() are case sensitive. Not getting my point ? let me show you.
this is our default text. “T” in The and “Q” in Quick is uppercase.
this time i type all lower case character in .StartsWith() method and lets see the result
$text.StartsWith("the quick")
and this time result is false. You need take care of it if you are going to use these methods in your scripts.
lets compare.. I hope everything is clear now.
How to fix it ???
to make these methods make case-insensitive add ,1 after the text. This ,1 is in igonecase switch which is Boolean, so 1 means is case-insensitive is ON
$text.StartsWith("the quick",1)
Bingo !!! now our condition is true.. :)
lets check if out text ends with “lazy dog”
$text.EndsWith("lazy dog")
The result is “True” which means our text ends with “lazy dog”
as i mentioned before that the text in these Methods take as case sensitive. in our current string “lazy dog” is in lower case let try to search with “Lazy Dog”
$text.EndsWith("Lazy Dog")
as expected the result is “False”
lets make it case-insensitive by ON the IgnoreCase switch
$text.EndsWith("Lazy Dog",1)
Bingoo !!! its true now ….
want to see the comparison? I bet you want…
In the screenshot you can see the original text and the methods with ignorecase and without ignorecase switch
Thanks
Aman Dhally
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.