首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >关于向字符串添加短划线的奇怪任务。PHP

关于向字符串添加短划线的奇怪任务。PHP
EN

Stack Overflow用户
提问于 2012-10-13 16:38:01
回答 1查看 366关注 0票数 2

我需要一个函数来做以下事情:

如果我有一个像这样的"2 1 3 6 5 4 8 7"字符串,我必须按照一些规则在数字对之间插入破折号。

规则很简单。

如果两个数字中的第一个数字比它后面的数字小,则在两个数字之间加一个短划线。做所有可能的组合,如果一对已经有破折号,那么它旁边的空格就不能有破折号。

基本上,我对上述字符串的结果是

代码语言:javascript
运行
复制
2 1-3 6 5 4 8 7
2 1-3 6 5 4-8 7
2 1 3-6 5 4 8 7
2 1 3-6 5 4-8 7
2 1 3 6 5 4-8 7

我确实创建了一个函数来做这件事,但我认为它相当慢,我不想用它来影响你的想法。如果可能的话,我想知道你们是如何思考这个问题的,甚至一些伪代码或代码也会很棒。

编辑1:这是我到目前为止所拥有的代码

代码语言:javascript
运行
复制
$string = "2 1 3 6 5 4 8 7";

function dasher($string){
   global $dasherarray;
   $lockcodes = explode(' ', $string);

   for($i = 0; $i < count($lockcodes) - 1; $i++){
      if(strlen($string) > 2){
         $left = $lockcodes[$i];
         $right = $lockcodes[$i+1];
         $x = $left . ' ' . $right;
         $y = $left . '-' . $right;
         if (strlen($left) == 1 && strlen($right) == 1 && (int)$left < (int)$right) {
            $dashercombination = str_replace($x, $y, $string); 
            $dasherarray[] = $dashercombination;
            dasher($dashercombination);
         }
      }
   }
   return array_unique($dasherarray);
}

foreach(dasher($string) as $combination) {
   echo $combination. '<br>';
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-13 17:15:07

也许这将有助于提供不同的方法来解析字符串。

代码语言:javascript
运行
复制
$str="2 1 3 6 5 4 8 7";
$sar=explode(' ',$str);
for($i=1;$i<count($sar);$i++)
  if($sar[$i-1]<$sar[$i])
    print substr_replace($str,'-',2*($i-1)+1,1) . "\n";

请注意,代码只要求字符串中有一位数字。

请注意,代码期望字符串按照您的示例格式化。最好是添加一些健全性检查(折叠多个空格,在开头/结尾去掉/修剪空白)。

我们可以通过查找字符串中的所有空格并使用它们索引子字符串进行比较来改进这一点,仍然假设只有一个空格分隔相邻的数字。

代码语言:javascript
运行
复制
<?php
$str="21 11 31 61 51 41 81 71";
$letter=' ';
#This finds the locations of all the spaces in the strings
$spaces = array_keys(array_intersect(str_split($str),array($letter)));

#This function takes a start-space and an end-space and finds the number between them.
#It also takes into account the special cases that we are considering the first or 
#last space in the string
function ssubstr($str,$spaces,$start,$end){
    if($start<0)
        return substr($str,0,$spaces[$end]);
    if($end==count($spaces))
        return substr($str,$spaces[$start],strlen($str)-$spaces[$start]);
    return substr($str,$spaces[$start],$spaces[$end]-$spaces[$start]);
}

#This loops through all the spaces in the string, extracting the numbers on either side for comparison
for($i=0;$i<count($spaces);$i++){
    $firstnum=ssubstr($str,$spaces,$i-1,$i);
    $secondnum=ssubstr($str,$spaces,$i,$i+1) . "\n";
    if(intval($firstnum)<intval($secondnum))
        print substr_replace($str,'-',$spaces[$i],1) . "\n";
}

?>

注意显式转换为整数,以避免按字典顺序进行比较。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12871441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档