Navigation
Synopsis Replace words in a string.
Description Suppose you are a book editor and want to ensure that all chapter and section titles are properly capitalized. Here is how to do this.
Examples
module demo::common::WordReplacement

import String;

// capitalize: convert first letter of a word to uppercase

public str capitalize(str word)  
{
   if(/^<letter:[a-z]><rest:.*$>/ := word){
     return toUpperCase(letter) + rest;
   } else {
     return word;
   }
}

// Capitalize all words in a string

// Version 1: capAll1: using a while loop

public str capAll1(str S)        
{
 result = "";
 while (/^<before:\W*><word:\w+><after:.*$>/ := S) { 
    result = result + before + capitalize(word);
    S = after;
  }
  return result;
}

// Version 2: capAll2: using visit

public str capAll2(str S)        
{
   return visit(S){
   	case /^<word:\w+>/i => capitalize(word)
   };
}
We start by introducing a helper function capitalize () that does the actual capitalization of a single word. See Rascal:Patterns/Regular for details about regular expression patterns.

Next we give two versions of a capitalization functions for a sentence:
  • capAll1 () uses a while loop to find subsequent words and to replace them by a capitalized version.
  • capAll2 () uses a Rascal:Visit to visit all words in the sentence and replace them by a capitalized version.
Here are some examples:
rascal>import demo::common::WordReplacement;
ok
rascal>capitalize("rascal");
str: "Rascal"
rascal>capAll1("turn this into a capitalized title")
str: "Turn This Into A Capitalized Title"
rascal>capAll2("turn this into a capitalized title")
str: "Turn This Into A Capitalized Title"
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.