Sign in to follow this  
Followers 0
hrodriguez106

Counting leading spaces in string

4 posts in this topic

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.

Share this post


Link to post
Share on other sites



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)

Share this post


Link to post
Share on other sites

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)

Share this post


Link to post
Share on other sites

SOLVED! Thanks for your replies.

Malkey it seems that this is all I needed, just couldn't figure out the systax.

StringRegExpReplace($arr[$i], "^( *)(.*)$", "\1") ; Captures leading spaces only.

Thanks,

H.

Share this post


Link to post
Share on other sites

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
Sign in to follow this  
Followers 0