I’m just a character in your dream

“I’m just a character in your dream. Check with that guy over there wearing the motorcycle helmet.”

~ a note from September 5, 2010

How to extract a substring near the Nth occurrence of a string or character in a string

A Scala substring example: I ran into a situation today where I wanted to get a string after the Nth occurrence of another string, in this case after the 6th occurrence of a “:” character. There are probably many ways to determine the Nth occurrence of a string in another string, but as a quick example, this is what I did.

First, I started with this string:

PHP: How to remove non-printable characters from strings

PHP FAQ: How do I remove all non-printable characters from a string in PHP?

I don’t know of any built-in PHP functions to remove all non-printable characters from a string, so the solution is to use the preg_replace function with an appropriate regular expression.

Scala functions to repeat a character n times (blank padding)

Earlier today I needed a function that would return a desired number of blank spaces so I could “pad” some output as desired. For some reason my mind went blank and I forgot about using a printf-style solution, and it quickly went to, “How can I write a Scala function to return n number of blank spaces?”

Note: If you just want the “best” solution, please scroll to the bottom of this article.

How to remove extended ASCII characters from Unix files with the 'tr' command

When working with text files on a Unix/Linux system, you'll occasionally run into a situation where a file will contain extended ASCII characters. These extended characters will generally appear to begin with ^ or [characters in your text files. For instance, the vi/vim editor will show ^M characters in DOS text files when they are transferred to Unix systems, such as when using the ftp command in binary transfer mode. Oftentimes, you'll want to easily delete these characters from your files.

How to process every character in a text file in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.4, “How to process every character in a text file in Scala.”


You want to open a text file and process every character in the file.


If performance isn’t a concern, write your code in a straightforward, obvious way:

How to process a Scala String one character at a time (with map, for, and foreach)

Scala FAQ: How can I iterate through each character in a Scala String, performing an operation on each character as I traverse the string?


Depending on your needs and preferences, you can use the Scala map or foreach methods, a for loop, or other approaches.

The map method

Here’s a simple example of how to create an uppercase string from an input string, using the map method that’s available on all Scala sequential collections: