我们得到了一条线。我们需要用PHP编写一个程序,使用内置函数查找字符串中最后一个单词的长度。 我们已经讨论了解决这个问题的方法 在这里 .本文讨论了PHP解决这个问题的方法。
null
例如:
Input : "php exercises" Output : 9 Input : "geeks for geeks" Output : 5
我们将主要使用PHP中的这三个内置函数来解决这个问题:
- substr()函数 :PHP中的这个内置函数用于提取字符串的一部分。
- strrpos()函数 :PHP中的这个内置函数用于查找字符串在原始字符串或其他字符串中的最后位置。它返回与字符串最后一次出现的位置相对应的整数值,并唯一地处理大写和小写字符。
- strlen()函数 :PHP中的这个内置函数用于查找字符串的长度。
使用上述内置函数解决这个问题的方法是首先使用strps()函数找到字符串中最后出现的空格的位置。在获得最后出现的空格的位置后,我们可以使用substr()函数轻松获得字符串中的最后一个单词,并将其存储在新的字符串变量中。最后,我们可以使用strlen()函数来查找字符串中最后一个单词的长度。
<?php // PHP code to find the length of last word // in a string // function to find length of last word function length_last_word( $string ) { // position of last occurring space // in the string $pos = strrpos ( $string , ' ' ); // if the string has only one word if (! $pos ) { $pos = 0; } else { $pos = $pos + 1; } // get the last word in the string $lastWord = substr ( $string , $pos ); // return length of last word return strlen ( $lastWord ); } // Driver Code print_r(length_last_word( 'geeksforgeeks' ). "" ); print_r(length_last_word( 'computer science portal' ). "" ); ?> |
输出:
13 6
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END