在字符串中查找公共字符 [英] Finding common characters in strings

查看:173
本文介绍了在字符串中查找公共字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这种方法来找到两个字符串中的公共字符,即$ a和$ r,但第一个字符不会被打印。此外,$已经收集常见的字符,并防止它们多次打印(我需要每个字符只打印一次),但它不是这样做。请告诉我我在做什么错误。

 <?php 
$ a =BNJUBCI CBDIDIBO
$ r =SBKJOJLBOU;
$ already =;
for($ i = 0; $ i< strlen($ r); $ i ++)
{
if(stripos($ a,$ r [$ i])!= FALSE)
{
if(stripos($ already,$ r [$ i])== FALSE)
{
$ already = $ already。$ r [$ i]
echoalready =。$ already。< br>;
echo $ r [$ i]。< br>;
}
}
}
?>


解决方案

使用!== FALSE 而不是!= FALSE 。问题是 stripos 返回0,如果needle在haystack的开始,0是falsy。通过使用!== ,你将强制它确保结果实际上是false,而不只是0。



这实际上列在文档中。



此函数可能会返回布尔值FALSE,但也可能返回一个非布尔值,计算结果为FALSE。有关详细信息,请阅读Booleans部分。使用===运算符测试此函数的返回值。



I am tring this method to find the common characters in two strings namely, $a and $r, but the first character isn't getting printed . Moreover the $already collects the common characters and prevents them from being printed for multiple times( I need each character to be printed once only) but it isn't doing so. Please tell me what errors I am making.

<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$already="";
for($i=0;$i<strlen($r);$i++)
{
   if (stripos($a,$r[$i])!=FALSE)
   {
        if (stripos($already,$r[$i])==FALSE)
        {
            $already=$already.$r[$i];
            echo "already=".$already."<br>";
            echo $r[$i]."<br>";
        }
   }
}
?>

解决方案

Use !==FALSE instead of !=FALSE. The problem is that stripos returns 0 if the needle is at the start of the haystack, and 0 is falsy. By using !== you are forcing it to ensure the result is actually false, and not just 0.

This is actually listed in the docs. An "RTFM" might be appropriate here.

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

这篇关于在字符串中查找公共字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆