Home > database >  Change "oo" to "00" in a string using some loop
Change "oo" to "00" in a string using some loop

Time:10-04

Need to hep to change multiple characters in a string using some loop without built-in functions in PHP.

<?php
       $givenString = "School";
       $i=0;
    while($givenString[$i]){
        $i  ;
        if($givenString[$i] == o){
        $givenString[$i] = 0;
        }
    }
    
    echo $givenString;
    ?>

Result: Sch0ol Required Result: Sch00l

CodePudding user response:

Because your loop logic is out of order. Feed in the string "ooooo" and you'll get "o0ooo" out. It skips the first letter because the first thing you do is move the index ahead, and it stops after the first replacement because you're testing the character that you just replaced, and "0" type-juggles to boolean as false.

Move $i to the end of the loop and you'll get "00000", but also Warning: Uninitialized string offset 6. This is because you're relying on the error to break the loop. You need to bound the loop on the length of the string, not the content.

So:

$givenString = "oooooo";
$i=0;
$c=strlen($givenString);
while($i<$c){
    if($givenString[$i] == 'o'){
        $givenString[$i] = 0;
    }
    $i  ;
}

echo $givenString;

or we can condense that with for loop:

$givenString = "oooooo";
$stringLength =strlen($givenString);

for( $i = 0; $i < $stringLength; $i   ){
    if($givenString[$i] == 'o'){
        $givenString[$i] = 0;
    }
}

echo $givenString;

For completeness, the un-quoted o in your post only works because pre-8.0 PHP assumed that unquoted constants were just "oopsies" meant to be strings and replaced them with their string equivalent, issuing a Notice like Notice: Use of undefined constant o - assumed 'o', which can potentially have serious side-effects.

This error also indicates that you're using a version of PHP that is no longer supported, and you should ensure that you are writing code on a supported version.

CodePudding user response:

In your current code, you are replacing all o to 0 which is off-track with respect to replacing oo to 00 and also skipping the current o at hand doesn't make sense. Also, as already pointed out, matching a string with a string is better than comparing with just o directly.


You can instead match o with o and check if string contained a previous o or not. If it did, mark both previous and current location as 0, or else, leave it as is. Since you didn't wish to use inbuilt functions, you can use null-coalescing operator(??) to check with the length of the string as well.

<?php

function modify($string){

  for($i = 1; ($string[$i] ?? false) !== false;   $i){
    if($string[ $i ] === 'o' && $string[$i - 1] === 'o'){
      $string[ $i ] = $string[$i - 1] = '0';
    }
  }
  
  return $string;
}

Online Demo

  • Related