简体   繁体   中英

How to replace the duplicated values in a string by a specific character?

How can I change the value of the duplicated character in a string?

if they are duplicated I want to have a specific value for that else if they are not, I also want to put a specific value for that too.

Scenario 1: Input: hello

Output: ..??.

Scenario 2:

Input: elephant Output: ?.?....

$str = "elephant";

$arr= str_split($str);

    for($i = 0; $i < count($arr); $i++) {  
     for($j = $i + 1; $j < count($arr); $j++) {  
        if($arr[$i] == $arr[$j]){
          
       }
     }  
    }

I really don't know on how will I change the value of it then implode them again.

If you don't care about speed that much try this:


<?php

function transform($str) {
    $arr= str_split($str);
    $counted = array_count_values($arr);
    
    foreach($counted as $letter => $times) {
      if($times == 1) {
          $str = str_replace($letter, ".", $str);
      }else {
          $str = str_replace($letter, "?", $str);
      }
    }
    return $str;
}

var_dump(transform("elephant")); // string(8) "?.?....."
var_dump(transform("hello"));    // string(5) "..??."

array_count_values will store the amount of time each value is present in the array, so for "elephant" it looks like this:

array(7) {
  ["e"]=>
  int(2)
  ["l"]=>
  int(1)
  ["p"]=>
  int(1)
  ["h"]=>
  int(1)
  ["a"]=>
  int(1)
  ["n"]=>
  int(1)
  ["t"]=>
  int(1)
}

So then it's as easy as iterating over this array, and calling str_replace with '.' if the counted value is 1, and '?' otherwise.

It can be improved to be more performable, but that's not the point of this question.

try this:

$str = "hello";
$arr = str_split($str);
$duplicates = array_unique(array_diff_assoc($arr,array_unique($arr)));
for($i = 0; $i < strlen($str); $i++) {
   if(in_array($str[$i], $duplicates)) {
      $str[$i] = '?';
   } else {
      $str[$i] = '.';
   }
}
echo $str;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM