Jump to content

Recommended Posts

Posted

Hello all, was wondering if there is a way to retrieve the leading number of spaces in a string? I'm using search and replace while modifying an XML file but I have not figured out how to preserve the amount of spaces preceding each line.

Thanks in advance,

H.

Posted

  On 6/28/2011 at 4:06 AM, 'hrodriguez106 said:

Hello all, was wondering if there is a way to retrieve the leading number of spaces in a string? I'm using search and replace while modifying an XML file but I have not figured out how to preserve the amount of spaces preceding each line.

Thanks in advance,

H.

One way!

$aString = '   Help'
$aCount = 0
For $1 = 1 To StringLen($aString)
    If StringMid($aString, $1, 1) = ' ' Then
        $aCount += 1
    Else
        ExitLoop
    EndIf
Next
MsgBox(0, 'Leading Spaces', $aCount)
Posted

If you can not figure out how not to delete the leading spaces on each line in the first place, then this example may give you some ideas.

Local $sLeadingSpaces, $strExLeadSpcs = "", $sNewStr
Local $str = " One leading space" & @CRLF & "   three leading spaces" & @CRLF & "  two leading spaces" & @CRLF & @TAB & "Line 4."
ConsoleWrite("Original String:" & @CRLF & $str & @CRLF & @CRLF)

Local $arr = StringSplit($str, @CRLF, 3)
Local $aLeadingSpaces[UBound($arr)] ; An array of leading spaces.

; Store leading spaces in an array, and remove leading spaces from each line.
For $i = 0 To UBound($arr) - 1
    $arr[$i] = StringReplace($arr[$i], @TAB, "      ") ; Replace @TAB with 8 spaces.
    $aLeadingSpaces[$i] = StringRegExpReplace($arr[$i], "^( *)(.*)$", "\1") ; Captures leading spaces only.
    ConsoleWrite("Line #" & ($i + 1) & " has " & StringLen($aLeadingSpaces[$i]) & " leading spaces." & @CRLF)
    $strExLeadSpcs &= StringStripWS($arr[$i], 1) & @CRLF ; Strip leading white spaces
Next
ConsoleWrite(@CRLF & "Modified String:" & @CRLF & $strExLeadSpcs & @CRLF)

; Replace leading spaces to each line
$arr = StringSplit(StringTrimRight($strExLeadSpcs, 2), @CRLF, 3)
For $i = 0 To UBound($arr) - 1
    $sNewStr &= $aLeadingSpaces[$i] & $arr[$i] & @CRLF
Next
ConsoleWrite("Re-constituted String:" & @CRLF & StringTrimRight($sNewStr, 2) & @CRLF)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...