Useful algorithms for String operations

Making a string of "********"

There is no method to make a string of one character, but it is easy to write one. This should go into some utility class that you keep handy.

static String fillStr(char c, int len){	
	char[] fill = new char[len];	  		// create a char array of "len" characters	
	Arrays.fill(fill, c);				// Fill the char array with all "c"s	
	return new String(fill);			// Create string using the char array
}

This is easily modified to printout headings that look like this: printHeading("List of all movies in collection",'*');
Which produces *************************************** * Listing of all movies in collection * ***************************************

static void printHeading(String heading, char c) {
	if (c == '\0') return;				// prepending a null character will stop the string from printing
	char[] fill = new char[heading.length()+4];
	Arrays.fill(fill, c);
	System.out.println(new String(fill));
	System.out.println(c + " " + heading + " " + c);
	System.out.println(new String(fill));
}

Splitting up a string into words

There are two built in ways to do this: String.split and StringTokenizer (in java.util)

1. String Tokenizer Class - read the JavaDoc for more info. This is a legacy class.
Useful methods: (automatically uses space as delimiter)

Example:

String text = "This is a string object.";
StringTokenizer chunks = new StringTokenizer(text);
while (chunks.hasMoreTokens() {
	System.out.println (chunks.nextToken());
}
StringTokenizer chunks = new StringTokenizer(text,"*");   // will use * as delimiter

2. String Split Method

String text = "This is a string object.";
String words[] = text.split(" ");	// use space as delimiter
for (int i=0; i < words.length; i++) {
	System.out.println (words[i]);
}

Most of the time String.split() is easier and more natural to use than StringTokenizer class.
The only possible useful StringTokenizer thing is the overloaded constructor: StringTokenizer(String str, String delim, boolean returnDelims) Why did I say this??

Splitting a string into words (writing your own method)

This would be used where you need to count the number of words, check each word if it is ...., etc.
It is quite simple in that it doesn't do anything with punctuation - it just treats it as if it is another letter.

   
//this is part of a function 
int pos=0;	//temporary variable needed for position
pos = str.indexOf(' ');
while (pos != -1) {
	String word = str.substring(0,pos);
	//do something with "word" here

	str = str.substring(pos+1);
	pos = str.indexOf(' ');
}

Note that the problem with this method is that the original string (str) is destroyed.

Processing every letter in a string

Use this when you need to look at each letter in a string, one after the other, for whatever reason.
Note that there is nothing in here yet to only look at alphabetic letters. So far "letter" means any character including spaces.

//obviously the string is stored in a String called str
char letter;
for (int i = 0 ; i < str.length(); i++ ) {
	letter = str.charAt(i);
	//process the letter here
}

Finding every occurrence of a certain word or substring in a string

There are many variations on the code below. Note that this algorithm does not take upper/lower case into consideration, nor does it handle whitespace.
This means that it will find all instances of "the" including in "theatrical" and "scythe", but it will not find "The".
To fix the case problem, just make the string lowercase before you look at it.
To fix the whitespace problem, look at the character following the search string to see if it is a space or punctuation (and make sure that there is a space in front of it as well!)

//this is part of a function 
String search = "the";
int count=0;
int pos=0;
pos = str.indexOf(search);
while (pos != -1) {
	String word = str.substring(0,pos);
	System.out.println(search + " " +  ++count);
	str = str.substring(pos+1);
	pos = str.indexOf(search);
}

How to replace a certain letter in a word or a string

	String str = "How important are Strings?";
	char letter = 'z';
	int n = 6;
	String newstr;

Method 1: String → array of characters → String

	char[] stuff = str.toCharArray();
	stuff[n] = letter;
	//one of the next two lines
	newstr = String.valueOf(stuff);
	//or
	newstr = new String(stuff);
	System.out.println(newstr);

Method 2: Slice and dice using substr()

		newstr = str.substring(0,n) + letter + str.substring(n+1, str.length());
		System.out.println(newstr);

Method 3: use StringBuffer's character replacement method

	StringBuffer sbuff = new StringBuffer(str);
	sbuff.setCharAt(n, letter);
	newstr = sbuff.toString();
	System.out.println(newstr);
	

Stripping out non-alphanumeric characters

We'll use a for loop to go through each character. If it's one that we want, add it to the end of new string

String str = "This is some!!! text%%^^&&%$. It costs $29.99";
String newStr = "";
for (int i=0; i < str.length(); i++) {
    char c = str.charAt(i);
	if (c >= 'A' && c <= 'Z') newStr = newStr + c;
	if (c >= 'a' && c <= 'z') newStr = newStr + c;
	if (c >= '0' && c <= '9') newStr = newStr + c;
	if (c == ' ') newStr = newStr + c;
}
System.out.println(newStr);  //will print: This is some text It costs 2999

Reverse a string easily

Don't forget that you can also "prepend" strings: you can add letters and words to the beginning of a string.

String reverse(String s1) {
   String s2 = "";
   for (int i=0; i < s1.length(); i++) {
       s2 = s1.charAt(i) + s2;
   }
   return s2;
}