How to replace just the first found space with tab for all lines in a variable?

Jim Ault jimaultwins at yahoo.com
Wed May 25 07:04:37 EDT 2011


On May 25, 2011, at 3:11 AM, Keith Clarke wrote:
> A simple requirement but I'm struggling with getting the structure  
> and syntax needed to replace only the first space character in each  
> line of a variable with a tab.
>
> I have a field of label-value pairs - and some of the values contain  
> spaces. This creates problems if I attempt a blanket approach of  
> 'replace space in tVariable' with tab.
>
> So, I tried iterating through each tLine of tVariable but get a  
> runtime error with 'replace space 1 in line tline with tab'. So, I'm  
> guessing that 'space' can't be used to set chunk expression scope.
>
> So, within each line, I'm iterating at character-level, with 'repeat  
> for each character tChar in the line, if tChar is space then...
>
> I've tried 'replace tChar with tab' and 'add tab after tChar' and  
> then 'delete tChar' but I get errors - probably because I'm trying  
> to delete the reference variable(?)
>
> I'm sure there is a nice efficient way to do this, so any advice on  
> structure, syntax or command usage would be greatly appreciated.

There are a few approaches  (working code below)

repeat for each line LNN in labelValueList
    put word 1 & tab & word 2 to -1 of LNN & cr after newList
end repeat
filter newList without tab  --optional for tab-only lines
filter newList without empty  --optional for 0 char lines


--- specific comments
>  I'm guessing that 'space' can't be used to set chunk expression  
> scope.

The chunk expression 'word' means 'space' as well as other white space  
chars
   get word 3 of line 4 of fld 5

If you wanted SPACES EXCLUSIVELY, then
      set the itemDel to space
and
    put item 1 & tab & item 2 to -1 of LNN & cr after newList

You can set the itemDel and the lineDel, but not the wordDelimiter

---  syntax errors  -- specific replace
replace space 2 in line k with tab -- makes no sense to LC
replace space 2 in line k of varLines with tab -- no sense either

---------  copy working code ----
on mouseup
    put fld 1 into tempp
    repeat for each line LNN in tempp
       put word 1 to -1 of LNN into cleanLine --trim
       put word 1 of cleanLine & tab & word 2 to -1 of cleanLine & cr  
after newList
    end repeat
    ;put newList
    --filter newList without tab  --to purge tab-only lines
-- or the following to keep tab-only lines as empty lines
    put 0 into prevNum
    repeat until the number of chars in newList is prevNum
       put the number of chars in newList into prevNum
       replace (cr & tab & cr) with ( cr & cr) in newList
    end repeat
    ;put newList
-- and purge empty if desired
    filter newList without empty
    ;put newList

end mouseup	
------- end copy code -------

Hope this helps.
Jim Ault
Las Vegas





More information about the use-livecode mailing list