Jump to content

Small Piece of Code to Replace a single character with another string or multiple characters

Recommended Posts

Hi All,

     I have written a UDF for one of my requirement which replaces a single character in string with a sub string/another character. 

     I am using this for my requirement by calling below function as StrReplace("C:\Software\Autoit\Substr","\","\\") and gives result as C:\\Software\\Autoit\\Substr

     Please let me know if this can be improvised or any mistakes to correct.   

; Function Name:    StrReplace($INPUT_STRING)
; Description:      This function is to replace a character with another in a string.
; Parameter(s):     $INPUT_STRING     - Original String Value
;                    $STR_2_FIND     - Single Character to find the $INPUT_STRING
;                    $STR_2_REPLACE     - Substring/Multiple Characters to replace in place of     $STR_2_FIND value
; Requirement(s):   Replacing one single Character in a string with multiple Characters
; Return Value(s):  success - Output string after replacing a character with required character
;                    failure - 0
; Author(s):        smartkey

    Local $OUTPUT_STRING = ""
    If StringLen($INPUT_STRING) > 0 Then
        If StringMid($INPUT_STRING,1,1) = $STR_2_FIND Then
            $OUTPUT_STRING = StringMid($INPUT_STRING,1,1)

        For $i=2 to StringLen($INPUT_STRING)
            If StringMid($INPUT_STRING,$i,1) = $STR_2_FIND Then
                $OUTPUT_STRING= $OUTPUT_STRING & StringMid($INPUT_STRING,$i,1)
        Return $OUTPUT_STRING
        Return 0

Edited by smartkey
Link to post
Share on other sites
  • Moderators

@smartkey AutoIt comes with a StringReplace function, to which yours seems very similar. What would this provide that the original does not, except two fewer parameters?

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to post
Share on other sites
  • 2 weeks later...

@JLogan3o13 before writing this function i have used StringReplace for replace \ with \\, but I could not get the output in right manner and now could not recall exact error. So I have tried in my own function, thought of sharing it for Single Character replacement(but not for multiple characters replacement). 

But after looking at your post, i tried again with StringReplace and it looks to be working for this also. I am not remembering what advantage the above function brought to me over StringReplace. 

Now I will change in my program with StringReplace and continue to see the challenges, if i come across any challenge, I will share in the same thread. Till then let me admit above function does not fetch any more than StringReplace. 

Thanks for the question about advantage and my apologies for wasting your time.

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By cdeb
      As for the object, in this case the StringReplace() function does not work for me.
      These are my steps:
      1) Extract the subject from an EML file.
       (the first character is an emoji )
      source from EML file: 
      $sSubject = "?utf-8?B?8J+TiCA1IG9mIHRoZSBCZXN0IFN0b2NrcyB0byBCdXkgZm9yIERlY2VtYmVy?=" 2) in this case I perform a decoding with _QuotedPrintable_DecodeEncodedWord()
      output is: 
      $sSubject = "?? 5 of the Best Stocks to Buy for December"  
      3) I perform StringReplace():
      $sSubject = StringReplace($sSubject, "??", "") or
      $sSubject = StringReplace($sSubject, Chr(63)&Chr(63), "")  
      But the characters ?? they are not replaced.
      Yet if I make an Asc of every character of the string with a for loop, are the first two characters really? that is 63
      For cycle
              Local $aArray = StringSplit($sSubject, "", $STR_NOCOUNT)         For $i = 0 To UBound($aArray)-1             ConsoleWrite($aArray[$i] & " - " & Asc($aArray[$i])& @CR)         Next Output:        
      ? - 63
      ? - 63
        - 32
      5 - 53
        - 32
      o - 111
      f - 102
        - 32
      t - 116
      h - 104
      e - 101
        - 32
      Does anyone have an explanation of why it doesn't work?
      Thank you all
    • By jmp
      I am adding labour charge to total paid amount using : 
      #include <IE.au3> #include <Array.au3> $oIE = _IEAttach ("Shop") $oTable = _IETableGetCollection ($oIE, 1) $aTableData3 = _IETableWriteToArray ($oTable) Local $sitem1 = $aTableData3[5][1] Local $sitem2 = $aTableData3[5][2] Local $lcharge = "10" ;add manualy using inputbox, becuase not generating online Local $atotPric = "Payable Total Price " Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.Innertext = $atotPric Then $iatotPric = $oTd.NextElementSibling.innertext MsgBox (0, "2", $iatotPric) EndIf Next $irCtotal = StringFormat("%.2f", $sitem1 + $sitem2 + $lcharge) $crTotp = StringReplace(_IEBodyReadHTML($oIE), $iatotPric, $irCtotal) _IEBodyWriteHTML ($oIE, $crTotp) But, It was also changing Total price, I want to change only Payable Total Price.

    • By milos83
      Default keyword for optional parameter is interpreted wrongly.
      ConsoleWrite(StringReplace("aa", "a", "b", Default, 1) & @CRLF) StringReplace ( "string", "searchstring/start", "replacestring" [, occurrence = 0 [, casesense = 0]] ) The code above will output ab even thou the default value for the occurrence is 0 (replace all).
      Of course using zero instead of Default will work fine.
    • By Amixg
      Hi! I have another problem with AutoIT.  You see, I'm still the one who's just starting out with this great programming language. I have a problem with AutoIT, it seems not to recognize the "StringReplace" function even when it is by default. The code was made half in KODA and half of my own. It is a software programmed for the Italian language (I am Italian) and translate the SMS language into Italian correct. Would you help me? Thanks in advance.
      #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> $hull = "hello" StringReplace($hull, "hello", "hellx") $Form1 = GUICreate("Linguaggio SMS A Italiano", 507, 498, 192, 124) $Edit1 = GUICtrlCreateEdit("", 24, 40, 465, 177) GUICtrlSetData(-1, "") $Label1 = GUICtrlCreateLabel("Inserisci qui il testo che non riesci a capire:", 24, 8, 205, 17) $Label2 = GUICtrlCreateLabel("Ecco il testo tradotto(non toccare questo campo):", 27, 237, 237, 17) $Edit2 = GUICtrlCreateEdit("", 24, 264, 465, 137) GUICtrlSetData(-1, "") $Button1 = GUICtrlCreateButton("Traduci", 104, 424, 249, 49) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 StringReplace(GUICtrlGetData($Label1), "qlc", "qualcuno") StringReplace(GUICtrlGetData($Label1), "qls", "qualcosa") StringReplace(GUICtrlGetData($Label1), "ke", "che") StringReplace(GUICtrlGetData($Label1), "x", "per") StringReplace(GUICtrlGetData($Label1), "pls", "per favore") StringReplace(GUICtrlGetData($Label1), "tu6", "tu sei") StringReplace(GUICtrlGetData($Label1), "zzz", "mi fai dormire") StringReplace(GUICtrlGetData($Label1), "hagn", "Buonanotte") StringReplace(GUICtrlGetData($Label1), "tvtb", "Ti voglio tanto bene") StringReplace(GUICtrlGetData($Label1), "tat", "Ti amo tanto") StringReplace(GUICtrlGetData($Label1), "lafs", "Amore a prima vista") StringReplace(GUICtrlGetData($Label1), "fli?", "Flirtiamo?") StringReplace(GUICtrlGetData($Label1), "msidt", "Mi sono innamorato di te") StringReplace(GUICtrlGetData($Label1), "ba", "Bacio") StringReplace(GUICtrlGetData($Label1), "midi", "Mi dispiace.") StringReplace(GUICtrlGetData($Label1), "ntm", "Non ti merito") StringReplace(GUICtrlGetData($Label1), "tdp", "Togliti dai piedi.") StringReplace(GUICtrlGetData($Label1), "amò", "Amore") StringReplace(GUICtrlGetData($Label1), "ap", "A presto!") StringReplace(GUICtrlGetData($Label1), "cmq", "comunque") StringReplace(GUICtrlGetData($Label1), "cvd", "Ci vediamo dopo") StringReplace(GUICtrlGetData($Label1), "Tvb", "Ti voglio bene") StringReplace(GUICtrlGetData($Label1), "nn", "non") StringReplace(GUICtrlGetData($Label1), "risp", "rispondimi") StringReplace(GUICtrlGetData($Label1), "cel", "cellulare") StringReplace(GUICtrlGetData($Label1), "dom", "qualcosa") StringReplace(GUICtrlGetData($Label1), "nm", "numero") StringReplace(GUICtrlGetData($Label1), "fv", "favore") StringReplace(GUICtrlGetData($Label1), "-male", "meno male") StringReplace(GUICtrlGetData($Label1), "disc", "discoteca") StringReplace(GUICtrlGetData($Label1), "se#", "settimana") StringReplace(GUICtrlGetData($Label1), "+ o -", "più o meno") StringReplace(GUICtrlGetData($Label1), "ts", "torno subito") StringReplace(GUICtrlGetData($Label1), "tvtbcoa", "Ti voglio tanto bene come amica") EndSwitch WEnd  
    • By Jibberish
      Junior Programmer here... 
      Not much experience with opening, changing and closing files.
      I am trying to replace strings in a Text file except StringReplace does not actually replace the text.
      Here is a sample of my code...
      #include <File.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> Local $iStrReturn = 0 Local $hFile Local $sText Local $sNewText ; Location of File to be read $sFileName = "C:\Temp\MyPlayer.exe.config" ; The default is FALSE. We want to change this to TRUE $bLoopChecked = True CheckBox() Func Checkbox() $hFile = FileOpen($sFileName,$FO_READ) ; Open file in read mode to get text If $hFile = -1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when Opening the file.") Exit EndIf FileSetPos($hFile, 0, 0) ; No idea if I need to do this, grasping at straws $sText = FileRead($hFile) ; Read the file into $sText If $sText = 1 Then MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading/writing the file.") Exit Else FileClose($hFile) ; Finished reading the file into $sText, so close the file. FileFlush($hFile) ; Manual says to use FileFlush between File Close and Open so here it is EndIf MsgBox(0,"Before Replacement",$sText) ; Displays the text read from the file to make sure something is there. ; Loop Check If $bLoopChecked = True Then ; Find the string return > 0 for success $iStrReturn = StringInStr('"<add key="LoopCheckbox" value=""False" />"', "False") ;MsgBox(0,"", "LoopCheckBox is " & $iStrReturn) If $iStrReturn > 0 Then ; If StringInStr returned > 0 the it found the string! ; The Meat of the code. This is where we have to replace "False" with "True" $sNewText = StringReplace($sText, '"<add key="LoopCheckbox" value="False" />"', '"<add key="LoopCheckbox" value="True" />"') MsgBox(0,"After Replacement",$sNewText) ; Display the text to see if it worked. $hFile = FileOpen($sFileName,$FO_OVERWRITE) ; Reopen the file to write to it, overwriting everything. FileWrite($hFile,$sNewText) ; Write the text to the file FileClose($hFile) ; Close the file EndIf EndIf EndFunc This is the file I am reading...
      <?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> </startup> <appSettings> <add key="LoopCheckbox" value="false"/> </appSettings> </configuration> I tried opening the file with $FO_UTF8 and $FO_UTF8_NOBOM but got errors opening the file.
      The MsgBox "After Replacement" shows the value is still false.
  • Create New...