Interview street Career Gear Programming challenge

Rahimanuddin's Blog

My solution to Interview street Career Gear Programming challenge -2 in PHP :

Question : Given an input string and a specified length, make the string center of a bigger string of length specified length and add stars on both sides.

Sample Input : apple, 21

Sample Output :  ********apple********

<?php
$sample = ReadStdin(‘Please input a string: ‘, “apple”);
$length_sp = ReadStdin(‘Please input specified length: ‘, 21);
echo center_string($sample, $length_sp);
function center_string($string, $specified_length) {
$str_len = strlen($string);

if ($str_len > $specified_length) {
return flase;
}
else if ($str_len == $specified_length) {
return $string;
}
else {
$starlen = $specified_length – $str_len;
$star_string_fr = str_repeat(“*”, ceil($starlen/2));
$star_string_bc = str_repeat(“*”, floor($starlen/2));
$return = $star_string_fr.$string.$star_string_bc;
return $return;
}
}

function ReadStdin($prompt, $valid_inputs, $default = ”) {
while(!isset($input) || (is_array($valid_inputs) && !in_array($input, $valid_inputs)) || ($valid_inputs == ‘is_file’ && !is_file($input))) {
echo $prompt;
$input = strtolower(trim(fgets(STDIN)));
if(empty($input) && !empty($default)) {
$input = $default;
}
}
return…

View original post 4 more words

Advertisements

Leave a comment

Filed under Random

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s