DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • Swift: Master of Decoding Messy JSON
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots
  • From HTTP to Kafka: A Custom Source Connector

Trending

  • Top 6 Benefits of AWS Certification
  • Security in the Age of MCP: Preventing "Hallucinated Privilege"
  • Managing, Updating, and Organizing Agent Skills
  • How SaaS Architectures Break at Scale — and the Engineering Decisions That Prevent It
  1. DZone
  2. Coding
  3. JavaScript
  4. Groovy Goodness: Replace Characters in a String with CollectReplacements

Groovy Goodness: Replace Characters in a String with CollectReplacements

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Sep. 11, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

We can use the collectReplacements(Closure) method to replace characters in a String. We pass a closure to the method and the closure is invoked for each character in the String value. If we return null the character is not transformed, otherwise we can return the replacement character.

def s = 'Gr00vy is gr8'

def replacement = {
    // Change 8 to eat
    if (it == '8') {
        'eat'
    // Change 0 to o
    } else if (it == '0') {
        'o'
    // Do not transform
    } else {
        null
    }
}
 

assert s.collectReplacements(replacement) == 'Groovy is great'Code written with Groovy 2.1.6

Groovy (programming language) Strings

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • Swift: Master of Decoding Messy JSON
  • Secrets in Code: Understanding Secret Detection and Its Blind Spots
  • From HTTP to Kafka: A Custom Source Connector

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook