am632

Replace repeat characters in string

5 posts in this topic

Hi,

I'm wanting to replace characters in a string which occure on more than 1 occasion, so for example if I have the following string.

XXXYYYYXXZZXXXXXUUU

So is there a function I can use to replace say 2 x's with the letter 'W' and 3 x's with the letter 'R' for example? but if there are 5 X's like in the example could this be replaced with the letters 'WR'

I had a look at all the string functions in the help file but I cant find anything that would be suitable. I essentially need to search the string starting from the beginning for the occurances because the string can change depending on some variables from the user.

 

Thanks

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I think this should be possible with StringReplace. Start with the longest:

$sString = StringReplace($sString, "xxxxx", "WR")
$sString = StringReplace($sString, "xxxx", "??")
$sString = StringReplace($sString, "xxx", "R")
$sString = StringReplace($sString, "xx", "W")

 

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

A precise use of StringReplace should do it (from left to right, always)

$str = "XXXYYYYXXZZXXXXXUUU"

$str = StringReplace($str, 'XXX', 'W')
$str = StringReplace($str, 'XX', 'R')
Msgbox(0,"", $str)

Edit
water I didn't see your post  :)

Edited by mikell

Share this post


Link to post
Share on other sites

Hi,

Thanks for that it works fine. I did originally try StringReplace but it didn't cross my mind to start with the longest string frist.

 

Thanks

Share this post


Link to post
Share on other sites

:)


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

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