String Manipulation
One thing that is very common in contest programming is the manipulation of strings. Languages like Java and C++ are great for all sorts of problems but I don't consider them very good at working with strings. Languages like PHP and Perl are more flexible for working with strings.
This is why I have chosen PHP as my language of choice for writing about string manipulation.
-------------------
Substrings
The substr function allows you to read from a part of the string. The substr function is a rather massive beast but it is very helpful. This function requires at least two parameters but it has an optional third parameter.
The first required parameter is the string you want to read from. The second parameter is the location you want to start reading from. The third parameter allows you to specify how many characters you want to read.
For example you want to read everything after the first 3 characters.
The second parameter is a 3 not a four because arrays and strings start being indexed at 0. The first character is located at index 0.Code:$text = "flying dutchmen"; $sub = substr($text,3); echo $sub; // ing dutchmen
If you just want to copy so many characters you can use the third parameter.
Example:
Here you start at the fourth character and copy 2 characters.Code:$text = "flying dutchmen"; $sub = substr($text,3,2); // in echo $sub;
If you include a negative number as the second index you will copy that many characters from the end.
Example:
This section starts at the end of the string and copies exactly three characters.Code:$text = "flying dutchmen"; $sub = substr($text,-3); // men echo $sub;
Replacing Strings
You can use the str_replace function to replace parts of strings.
The function prototype for str_replace is:
All occurrences of search in source will be replaced with replace.string str_replace(search,replace,source);
Example:
Note this function is case sensitive. If you want a case-insensitive replace try the str_ireplace function. This function has the same prototype as str_replace.Code:$text = "Hello Joe! How is going Joe!"; $text = str_replace("Joe","Flying Dutchmen",$text); echo $text;
Example:
Also their is an optional fourth parameter that counts how many times a word was replace.Code:$text = "Hello Joe! How is going Joe!"; $text = str_ireplace("Joe","Flying Dutchmen",$text); echo $text;
Example:
It can be useful to work with ASCII characters and ASCII numbers. The ord function converts a character to it's ASCII equivalent. The chr function takes a ASCII number and converts it to the equivalent character.Code:$text = "This is a this this this long pointless string. This string has very bad this grammar."; $count = str_ireplace("This","****",$text); echo "You have sweared $count times.";
Example:
You can use the strlen function to find the length of a string. Say you want to print each char of a string on it's own line to the console.Code:$a = ord("a"); echo $a . " = "; $a = chr($a); echo $a;
Example:
Trimming whitespaceCode:$text = "flying dutchment"; for ($i=0;$i<strlen($text);$i++) { echo "$i: $text{$i}\n"; }
If your code requires your input to be formatted in a certain way, and the user gives it to you wrong, bad things could happen. By using trim functions to remove white space you can avoid problems.
The trim function removes all white space from both ends of the string. The rtrim and ltrim functions remove white space from the right and left of the string respectively.
Changing case
If you require all your input to be in a certain case you can use the strtoupper and the strtolower to change the casing. The strtoupper function converts your string into uppercase. The strtolower function converts your string into lowercase.
Careful use of the string functions can make sure you get perfect on a contest question. If your output is off by one space, or your string is in lowercase, when it should be in uppercase, you get 0.
Number Format
Another common question in contests is having your numbers in a very precise format. You can use the number_format function to format your numbers appropriately. The function prototype appears like this:
First you specify the number to format, how many decimal places to format it to, what the decimal separator should be and what the thousands_separator should be.string number_format(number,decimal_places,decimal_separa tor,thousands_separator)
If the question asks for output in German format as shown below and you give the answer in British, or American format you get 0.
Example of German format:
If the specifications asks you for 2 decimal points and you use 3 you get zero.3.567,89
There is a lot that PHP can do with strings, and I strongly encourage you to have a look at these web sites:
PHP String Functions
PHP: Strings - Manual
From reading this, I hope that you learned quite a bit about strings in PHP. I also want to leave you with this message:
Always, read the program specifications very closely. It's either all or nothing. If you miss a space, or off by one decimal place you get nothing.
Look at your languages manual for more you can do with strings. It's a fascinating area of study.
I would like to leave you with some problems (and feel free to register at these judge web sites). They are great for developing your programming skill.
WERTYU
Fmt
Do the Shuffle scroll down to question 2.
Anagram Checker scroll down to question 4.
AmeriCanadian scroll down to question 2.
Baby Diff
Working Directory
There is just way too much to cover here. Have a good look at your languages manual when working these problems.
Enjoy,
James![]()
Last edited by chili5; 03-18-2009 at 08:45 AM.
nicely done![]()
Thanks
I'm going for a tutorial on some graph theory next.![]()
As always, very nice tutorial and very informative! +rep
I like it.. Great job
Replacing Strings
You can use the str_replace function to replace parts of strings.
The function prototype for str_replace is:
All occurrences of search in source will be replaced with replace.
This is an interesting function. I'm wondering if it can loop through and replace lines in a file as well?
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein
Well I don't think you can just change parts of the file, but you can load it into memory and then modify it.
Original input file:
Output file:This is this is this.
This this this this.
This this this this.
Anything that was "This" or "this" has become "****".**** is **** is ****.
**** **** **** ****.
**** **** **** ****.
Code:
Code:<?php
$data = file_get_contents("test.txt"); // read into a string
$data = str_ireplace("This","****",$data); // replace all instances of This or this with ****
$data = split("\n",$data); // split into an array at the new line
// erase the file
$fp = fopen("test.txt","w");
// walk the array printing back to the file
foreach ($data as $d) {
$d = str_replace("\n","\n\r",$d); // only include this line if you are using windows
fwrite($fp,$d);
}
fclose($fp);
?>
Cool. I guess thats how they do find-replace on editor or something similar.
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein
No they would use regular expressions for that. I didn't even mention regular expressions. The regular expressions give even more control with strings. This tutorial was to show how much power you have without knowing what a regular expression is.
Cool! thanks. ill read that reg exp..thread.![]()
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks