Friday, June 5, 2015

#81 : String handling with Substring function

Substring function is available in nearly all the programming and scripting languages. This function is best suited for traversing each character or set of characters of string based on length and rank of character to start with. In fact, you can do chopping of certain string from the complete string. I have used substring a lot with T-SQL Programming. Let us take a look how substring can be used in Powershell.

1. Chop last three characters from a string using substring. If string is less than 3 character, return whole string.

#-------------------------------------------------------#
#--Function to find last three characters of a string --# 
#-------------------------------------------------------#

function chop-last-three([string]$str)
{
 if ( $str.length -ge 3 ) 
 {
  echo $str.substring($str.length - 3, 3) 
 } 
 else 
 {
  echo $str
 }
}


chop-last-three "ABCDEFGHIJKLMNOP" 



2. Chop first three characters of a string using substring. If string is less than 5 characters, return whole string.

#-------------------------------------------------------#
#--Function to find first three characters of a string --# 
#-------------------------------------------------------#

function chop-first-three([string]$str)
{
 if ( $str.length -ge 3 ) 
 {
  echo $str.substring(0, 3) 
 } 
 else 
 {
  echo $str
 }
}


chop-first-three "ABCDEFGHIJKLMNOP"

That's all for today. You may ask questions if you want.
Thanks for reading this article!

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. I believe chop-last-three can also be accomplished using:
    $str="ABCDEFGHIJKLMNOP"; $str.Substring(($str.Length - [System.Math]::Min(3, $str.Length)), [System.Math]::Min(3, $str.Length))

    and chop-first-three can be accomplished using:
    $str="ABCDEFGHIJKLMNOP"; $str.Substring(0, [System.Math]::Min(3, $str.Length)

    ReplyDelete

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...