Jump to content
TrashBoat

Add spaces between string elements

Recommended Posts

TrashBoat

hey i would like to know if its possible to take a string like this

$string = "onethousandninehundredeightyfive"

and convert it into:

$string = "one thousand nine hundred eighty five"

i have something going on here but its no use

$string = "onethousandninehundredeightyfive"
Global $array[9] = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
Global $array1[19] = ['onethousand', 'twothousand', 'threethousand', 'fourthousand', 'fivethousand', 'sixthousand', 'seventhousand', 'eightthousand', 'ninethousand','tenthousand','hundred', 'twohundred', 'threehundred', 'fourhundred', 'fivehundred', 'sixhundred', 'sevenhundred', 'eighthundred', 'ninehundred']
MsgBox(0, 0, AddSpaces($string))


Func AddSpaces($string)
    Local $finalStr
    $length = StringLen($string)
    For $x = 0 To $length
        Local $trim = StringTrimRight($string, $x)
        For $h = 0 To 18
            If $trim = $array1[$h] Then
                $finalStr = $finalStr & " " & $trim
                $string = StringTrimLeft($string, $h)
                $length = StringLen($string)
            EndIf
        Next

        For $z = 0 To 8
            If $trim = $array[$z] Then
                $finalStr = $finalStr & " " & $trim
                $string = StringTrimLeft($string, $z)
                $length = StringLen($string)
            EndIf
        Next
    Next
    Return $finalStr
EndFunc   ;==>AddSpaces

 

Share this post


Link to post
Share on other sites
TheXman

Here's one way that it could be done:

example()

Func example()
    Const $kData = "onethousandninehundredeightyfivefiftysixninetyfour"

    Local $s = $kData
    $s       = StringRegExpReplace($s, "(?i)(zero|one|two|three|four(?!ty)|five|six(?!ty)|seven(?!y)|eight(?!y)|nine(?!ty))", "\1 ")
    $s       = StringRegExpReplace($s, "(?i)(twenty|thirty|fourty|fifty|sixty|seventy|eighty|ninety)", "\1 ")
    $s       = StringRegExpReplace($s, "(?i)(hundred|thousand)", "\1 ")

    ConsoleWrite($s & @CRLF)
EndFunc

 

Edited by TheXman
  • Like 1

Whoever said that there's no such thing as a dumb question, probably asked a lot of DUMB questions.  Dumb questions are ones that you can easily find the answer to on your own.

Share this post


Link to post
Share on other sites
TrashBoat

ughh.. what are those (?i) i want to know i understand the (?!y) and (?!ty) , and thanks it works perfectly!

Share this post


Link to post
Share on other sites
TheXman
17 minutes ago, TrashBoat said:

ughh.. what are those (?i) i want to know i understand the (?!y) and (?!ty) , and thanks it works perfectly!

https://www.autoitscript.com/autoit3/docs/functions/StringRegExp.htm

(?i)  = Caseless: matching becomes case-insensitive from that point on.


Whoever said that there's no such thing as a dumb question, probably asked a lot of DUMB questions.  Dumb questions are ones that you can easily find the answer to on your own.

Share this post


Link to post
Share on other sites
Melba23

TheXman,

I would add the space before the detected string, not after - think of "nine" and "nineteen".

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
TheXman
5 minutes ago, Melba23 said:

I would add the space before the detected string, not after - think of "nine" and "nineteen".

@Melba23

Point taken.  My suggestion doesn't cover a myriad of additional possibilities or requirements.  But to your point, yes, there are several ways that it could have been accomplished. :)

Since "teens" weren't a part of the request, I didn't take them into account.  My solution was meant only to be as accurate as the request itself.  I try not to make any assumptions. :D

However, I did add "thousand" to the example just to point out that it was easy to expand upon the solution, if necessary.


Whoever said that there's no such thing as a dumb question, probably asked a lot of DUMB questions.  Dumb questions are ones that you can easily find the answer to on your own.

Share this post


Link to post
Share on other sites
TrashBoat

yeah ive added them myself no need

$s       = StringRegExpReplace($s, "(?i)(ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)", "\1 ")

 

Share this post


Link to post
Share on other sites
mikell
24 minutes ago, Melba23 said:

I would add the space before the detected string, not after - think of "nine" and "nineteen".

As the regex engine reads the pattern left to right it could be done like this  :)

$string = "nineteenthousandninehundredninetynine"

Local $pattern
$pattern &= "(?i)("
$pattern &= "hundred|thousand|twenty|ten|eleven|twelve|"
$pattern &= "thirty|fourty|fifty|sixty|seventy|eighty|ninety|"
$pattern &= "thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|"
$pattern &= "zero|one|two|three|four|five|six|seven|eight|nine"
$pattern &= ")"

$s = StringRegExpReplace($string, $pattern, "$1 ")
Msgbox(0,"", $s)

 

  • Like 3

Share this post


Link to post
Share on other sites
TheXman
1 hour ago, Melba23 said:

I would add the space before the detected string, not after - think of "nine" and "nineteen".

 

Slightly modified version that uses @Melba23's suggestion:

#include <Constants.au3>

example()

Func example()
    Const $kData = "onethousandninehundredeightyfivefiftysixninetyfour"
    Const $kData2 = "nineteenthousandninehundredeightyfivefiftysixninetyfourfourteententhousand"

    Local $s = $kData2
    $s = StringRegExpReplace($s, "(?i)(?<! )(zero|one|two|three|four|five|six|seven|eight|nine|ten)", " \1")
    $s = StringRegExpReplace($s, "(?i)(?<! )(eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)", " \1")
    $s = StringRegExpReplace($s, "(?i)(?<! )(twenty|thirty|fourty|fifty|sixty|seventy|eighty|ninety)", " \1")
    $s = StringRegExpReplace($s, "(?i)(?<! )(hundred|thousand|million|billion)", " \1")
    $s = StringStripWS($s, $STR_STRIPLEADING)

    ConsoleWrite($s & @CRLF)
EndFunc

 

(?<! ) = Only do the replacement if there isn't already a leading space.

;)

Edited by TheXman

Whoever said that there's no such thing as a dumb question, probably asked a lot of DUMB questions.  Dumb questions are ones that you can easily find the answer to on your own.

Share this post


Link to post
Share on other sites
iamtheky

yours still struggles where there is a match inside of your match

e.g. the following string returns  "twomilli oneight thousand four hundred fifty three" in your script, but splits correctly with @mikell's (after adding million to the lead the pattern)

$string = "twomillioneightthousandfourhundredfiftythree"

Local $pattern
$pattern &= "(?i)("
$pattern &= "million|hundred|thousand|twenty|ten|eleven|twelve|"
$pattern &= "thirty|fourty|fifty|sixty|seventy|eighty|ninety|"
$pattern &= "thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|"
$pattern &= "zero|one|two|three|four|five|six|seven|eight|nine"
$pattern &= ")"

$s = StringRegExpReplace($string, $pattern, "$1 ")
Msgbox(0,"", $s)

 

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites
TheXman
4 minutes ago, iamtheky said:

yours still struggles where there is a match inside of your match

Nice catch! :)


Whoever said that there's no such thing as a dumb question, probably asked a lot of DUMB questions.  Dumb questions are ones that you can easily find the answer to on your own.

Share this post


Link to post
Share on other sites
mikell

Complication is not necessary
As I said before, the regex engine reads the pattern left to right, and after a match/replacement it doesn't go backwards
Simple example :

$string = "abcdefghi"

$pattern = "(\w{2}|\w)"

$s = StringRegExpReplace($string, $pattern, "$1.")
Msgbox(0,"", $s)

;)

Share this post


Link to post
Share on other sites
jchd

I believe to have answered the OP question in the other thread devoted to conversion "text to number".


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

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

  • Similar Content

    • JuanFelipe
      By JuanFelipe
      Hello friends, I would like to know how to open a GUI from another GUI, I did it the way I leave the attached code, but when closing the second GUI they all close, they could help me to solve this problem without compiling another script. Thank you #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> $Form1 = GUICreate("Form1", 173, 126, 192, 124) $Button1 = GUICtrlCreateButton("Button1", 16, 24, 75, 25) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 _form2() EndSwitch WEnd ;================================================= GUI 2 Func _form2() $Form1 = GUICreate("Form2", 615, 437, 192, 124) GUISetState(@SW_SHOW) While 2 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd EndFunc  
    • bowker
      By bowker
      Hi! Is there a way for me to set the value for my slider? I am getting the value for my slider with
       
      Local $strText = _UIA_getPropertyValue($oUIElement, $UIA_LegacyIAccessibleValuePropertyId) MsgBox(0,"",$strText)  
    • nacerbaaziz
      By nacerbaaziz
      Hello
      Can we pause and resume the download in the InetGet function?
      If is possible, what is the solution please?
      I used this code To manage the download

      #include <INet.au3> func _downloader($name, $linc, $filepath, $RTLF = false, $link = false) global $downloader = GUICreate("downloader", 400, 200, -1, -1, $WS_CLIPCHILDREn, $RTLF, $link) global $path = $filePath $labelTxt = GUICtrlCreateLabel("downloading " & $name, 50, 10, 200, 20) global $labelTxt0 = GUICtrlCreateLabel("downloaded size 0 MB " & "OF 0 MB", 50, 60, 300, 20) global $Progress = "" global $sText = ""     For $i = 1 To Random(5, 20, 1) ; Return an integer between 5 and 20 to determine the length of the string.         $sText &= Chr(Random(65, 122, 1)) ; Return an integer between 65 and 122 which represent the ASCII characters between a (lower-case) to Z (upper-case). next global $labelTxt2 = GUICtrlCreateInput("0%", 50, 80, 50, 20) _GUICtrlEdit_SetReadOnly(-1, true) GUIStartGroup("") global $beep = GUICtrlCreateCheckBox("use the progress beep notification", 150, 120, 200, 20) GUIStartGroup("") $button = GUICtrlCreateButton("Cancel', 130, 150, 180, 25, 0x01) $iIndex = 0 global $Target global $url GUIStartGroup("") global $Progress = GUICtrlCreateProgress(50, 90, 150, 20) global $Target = $filepath global $url = $linc global $path = $filepath global $hDownloadNo = _RSMWare_GetData($url, $Target) global $status = false AdlibRegister("SetProgress") global $onprogress = false, $curent = false GUISetState(@sw_Show) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE, $button $asc = MsgBox(4132,"exit download?","if you click yes the downloading will be cancel, do you want to cancel it ?") if $asc = 6 then AdlibUnRegister("SetProgress") GUIDelete() If $hDownloadNo <> 0 Then InetClose($hDownloadNo) exitLoop endIf EndSwitch if $status = -1 then $status = 0 $hDownloadNo = _RSMWare_GetData($url, $Target) $onprogress = false $curent = false elseIf $Status = 1 then $status = $path GUIDelete() AdlibUnRegister("SetProgress") exitLoop endIf WEnd return $status endFunc Func _RSMWare_GetData($url, $Target) Local $hDownload = InetGet($url, $Target, 1, 1) Return $hDownload EndFunc ;==>_RSMWare_GetData Func SetProgress() Local $state If $hDownloadNo <> 0 Then $state = InetGetInfo($hDownloadNo) If @error = 0 Then $infor = "downloaded size " & Round(Execute(InetGetInfo($hDownloadNo, $INET_DOWNLOADREAD) / 1048576), 2) & " MB of " & Round(Execute(InetGetInfo($hDownloadNo, $INET_DOWNLOADSIZE) / 1048576), 2) & " MB " $onprogress = Round(Ceiling(($state[0] / $state[1]) * 100)) if not (InetGetInfo($hDownloadNo, $INET_DOWNLOADSIZE) = 0) then if $onProgress <= 0 then $onProgress = 0 GUICtrlSetData($Progress, $onProgress) GUICtrlSetData($labelTxt0, $infor) GUICtrlSetData($labelTxt2, $onProgress & "%") if _isChecked($beep) then if $onprogress > $curent then beep((100 + $onprogress * 20), 100) $curent = $onprogress endIf endIf endIf If $state[2] Then If $state[3] Then InetClose($hDownloadNo) $status = 1 else InetClose($hDownloadNo) $status = -1 endIf endIf EndIf endIf EndFunc ;==>SetProgress
    • VollachR
      By VollachR
      Hi,
      I'm looking for a way to take a number value from a Row2 of a 2D array and according to this check if files that appear in rows 3-11 in the array exists.
      For example, if the number in Row2 is 5 I need to check for the files in Row 3-6 only, if it is 6 than rows 3-7 and so on.
      I thought on using a FOR loop but I have very little experience with those.
      Can you suggest the best way to do what I need?
      BTW, the files in Rows 3-11 will usually have blank value for any row above the number in Row2 (e.g. Row2 = 5 so Rows3-6 will have values but 8-11 be empty), The values I need are in Column 1 of the array, the name of the key from the INI file that the array was created from is in Column 0.
      Full Example:
      Row2 of Array:
      Col0 = Games# - Col1 = 5
      Rows3-6
      Col0 = Exe2 - Col1 = Path To File
      Col0 = Exe3 - Col1 = Path To File
      Col0 = Exe4 - Col1 = Path To File
      Col0 = Exe5 - Col1 = Path To File
      I need that if Row2 is 5 to check these above for rows if the file exists, if it was 6 then the next row as well and so on up until number 10 in Row2 as it can't go above 10.
      So basically for whatever number in Row2 from 2-10 need to check 1-9 rows from 3-11 to see if the files in Col1 exists and if any of them don't exist it should call a function that shows an error message.
      I'm pretty sure I have the first line of the for look correct:
      For $i = 1 To $aAIO[2][1] Just not sure how to continue from there, also not sure if $i should be equal 1 or 2.
      Help will be appreciated.
    • VollachR
      By VollachR
      Hi,
      I've written a specialty INI file editor for a specific set of INI files related to a bigger script I'm working on.
      I'm trying to create a verification script that checks the ini files structure and format and gives an error if they are not in expected format.
      What I did so far is create a couple of custom arrays, each with the list of Sections expected in the files and I use IniReadSectionNames in order to read the sections from the selected INI file and compare it to the array.
      It works fine, excepts it only gives an error if one or more of the sections in the custom array is missing, if they all exist but there are other additional sections that shouldn't be there it doesn't give an error and continue to open the editor screen.
      Here are the relevant part of my script:
      The Custom Verification Arrays:
      ;Creating Arrays for INI Verification Global $aSettingsVerify[7] $aSettingsVerify[1] = "Conversion" $aSettingsVerify[2] = "AIO" $aSettingsVerify[3] = "Data" $aSettingsVerify[4] = "Redist" $aSettingsVerify[5] = "Split" $aSettingsVerify[6] = "Autorun" Global $aDataVerify[6] $aDataVerify[1] = "Compression" $aDataVerify[2] = "Exclude" $aDataVerify[3] = "LangExclude" $aDataVerify[4] = "PreCommands" $aDataVerify[5] = "PostCommands" The IniReadSectionNames verification part:
      Case $OK If StringInStr($ActiveConfig, "Settings.ini") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aSettingsVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) SettingsGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf If StringInStr($ActiveConfig, "Data") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aDataVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) DataGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf The Function that performs the compare: (Found it in another thread on this forums somewhere by using Google Search)
      ;Compares Imported INI file with the Verification array Func _ArrayCompare(ByRef $a1, ByRef $a2) Local $nOldSize = UBound($a2) Local $a3[$nOldSize], $nNewSize = $nOldSize For $i = 0 To UBound($a1) - 1 For $j = 0 To $nOldSize - 1 If Not $a3[$j] And ($a1[$i] = $a2[$j]) Then $a3[$j] = 1 $nNewSize -= 1 EndIf Next Next Local $a4[$nNewSize], $j = 0 For $i = 0 To $nOldSize - 1 If Not $a3[$i] Then $a4[$j] = $a2[$i] $j += 1 EndIf Next Return $a4 EndFunc ;==>_ArrayCompare  
      Any way to make a check if there are sections other than the ones in the Verification Array and produce an error?
      Thanks
×