hrodriguez106 Posted June 28, 2011 Posted June 28, 2011 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.
JoHanatCent Posted June 28, 2011 Posted June 28, 2011 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)
Malkey Posted June 28, 2011 Posted June 28, 2011 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)
hrodriguez106 Posted June 28, 2011 Author Posted June 28, 2011 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.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now