Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

String Manipulation

case sensitive string

  • Please log in to reply
10 replies to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 18 March 2009 - 07:21 AM

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.

$text = "flying dutchmen";
$sub = substr($text,3);
echo $sub; // ing dutchmen

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.

If you just want to copy so many characters you can use the third parameter.

Example:

$text = "flying dutchmen";
$sub = substr($text,3,2); // in
echo $sub;

Here you start at the fourth character and copy 2 characters.

If you include a negative number as the second index you will copy that many characters from the end.

Example:

$text = "flying dutchmen";
$sub = substr($text,-3); // men
echo $sub;

This section starts at the end of the string and copies exactly three characters.

Replacing Strings

You can use the str_replace function to replace parts of strings.

The function prototype for str_replace is:

string str_replace(search,replace,source);


All occurrences of search in source will be replaced with replace.

Example:

$text = "Hello Joe! How is going Joe!";
$text = str_replace("Joe","Flying Dutchmen",$text);
echo $text;

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.

Example:

$text = "Hello Joe! How is going Joe!";
$text = str_ireplace("Joe","Flying Dutchmen",$text);
echo $text;

Also their is an optional fourth parameter that counts how many times a word was replace.

Example:

$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.";

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.

Example:

$a = ord("a");
echo $a . " = "; 
$a = chr($a);
echo $a;

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.

Example:

$text = "flying dutchment";

for ($i=0;$i<strlen($text);$i++) {
	echo "$i: $text{$i}\n";
}

Trimming whitespace

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:

string number_format(number,decimal_places,decimal_separator,thousands_separator)


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.

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:

3.567,89


If the specifications asks you for 2 decimal points and you use 3 you get zero.

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 :)
  • 2

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 18 March 2009 - 07:36 AM

nicely done :)
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 18 March 2009 - 07:50 AM

Thanks :)

I'm going for a tutorial on some graph theory next. :)
  • 0

#4 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 18 March 2009 - 08:13 AM

As always, very nice tutorial and very informative! +rep
  • 0

#5 Guest_Jaan_*

Guest_Jaan_*
  • Guest

Posted 18 March 2009 - 09:36 AM

I like it.. Great job
  • 0

#6 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 18 March 2009 - 09:37 AM

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?
  • 0

#7 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 18 March 2009 - 10:28 AM

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:

This is this is this.
This this this this.
This this this this.


Output file:

**** is **** is ****.
**** **** **** ****.
**** **** **** ****.


Anything that was "This" or "this" has become "****".

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);
?>

  • 0

#8 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 18 March 2009 - 10:33 AM

Cool. I guess thats how they do find-replace on editor or something similar.
  • 0

#9 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 18 March 2009 - 10:36 AM

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.
  • 0

#10 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 18 March 2009 - 10:43 AM

Cool! thanks. ill read that reg exp..thread. ;)
  • 0

#11 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 24 March 2009 - 02:11 PM

Nice tutorial - and thanks for referencing mine :)
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download