+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: String Manipulation

  1. #1
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    String Manipulation

    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.

    Code:
    $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:

    Code:
    $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:

    Code:
    $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:

    Code:
    $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:

    Code:
    $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:

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

    Code:
    $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:

    Code:
    $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_separa tor,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
    Last edited by chili5; 03-18-2009 at 08:45 AM.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Join Date
    Jul 2006
    Posts
    16,491
    Blog Entries
    75
    Rep Power
    143

    Re: String Manipulation

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

  4. #3
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Re: String Manipulation

    Thanks

    I'm going for a tutorial on some graph theory next.

  5. #4
    Jordan Guest

    Re: String Manipulation

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

  6. #5
    Jaan Guest

    Re: String Manipulation

    I like it.. Great job

  7. #6
    fread's Avatar
    fread is offline Programming God
    Join Date
    Nov 2008
    Location
    Caribbean
    Posts
    654
    Blog Entries
    1
    Rep Power
    16

    Re: String Manipulation

    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

  8. #7
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Re: String Manipulation

    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:

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

  9. #8
    fread's Avatar
    fread is offline Programming God
    Join Date
    Nov 2008
    Location
    Caribbean
    Posts
    654
    Blog Entries
    1
    Rep Power
    16

    Re: String Manipulation

    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

  10. #9
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Re: String Manipulation

    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.

  11. #10
    fread's Avatar
    fread is offline Programming God
    Join Date
    Nov 2008
    Location
    Caribbean
    Posts
    654
    Blog Entries
    1
    Rep Power
    16

    Re: String Manipulation

    Cool! thanks. ill read that reg exp..thread.
    Perfection of means and confusion of ends seem to characterize our age. Albert Einstein

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Simple String manipulation!
    By madskillsmonk in forum Python
    Replies: 5
    Last Post: 03-09-2011, 06:07 PM
  2. C++ String Manipulation
    By skastu01 in forum C and C++
    Replies: 2
    Last Post: 08-23-2010, 09:42 AM
  3. C# trimming string or string manipulation
    By Siten0308 in forum C# Programming
    Replies: 3
    Last Post: 01-05-2010, 09:37 PM
  4. Replies: 5
    Last Post: 04-04-2008, 06:04 AM
  5. [Help] String manipulation.
    By afiser in forum Visual Basic Programming
    Replies: 1
    Last Post: 05-31-2007, 01:24 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts