Home > Article > Backend Development > How to find the first non-repeating character in a given string via PHP
A new week has begun again~ Everyone should know that the operation of strings in PHP is the most critical and basic part of programming. In the following articles, we will successively introduce to you the basic operations of strings. , I believe there are always skills you can master~
Then the topic of this article is "Write a PHP program to find the first non-repeating character in a given string".
For non-repeating characters, there should be no need to explain too much. For example, in the string "adicvdda", the first non-repeating character visible to the naked eye is i, because the characters a and d are both repeated.
Now we will introduce to you how to implement this operation through PHP.
The PHP code is as follows:
<?php function find_non_repeat($word) { $chr = null; for ($i = 0; $i <= strlen($word); $i++) { if (substr_count($word, substr($word, $i, 1)) == 1) { return substr($word, $i, 1); } } } echo find_non_repeat("Green")."<br>"; echo find_non_repeat("abcdea")."<br>";
The output result is:
G b
That is to say, the first non-character string in the given string "Green" The repeating character is G, and the first non-repeating character in "abcdea" is "b".
In the above code, we mainly traverse each character in the string through a for loop, and then compare it.
PHP strlen()
The function is used to return the length of the string. The return value is the length of the string if successful, or 0 if the string is empty.
PHP substr_count()
The function is used to count the number of times a substring appears in a string. The return value is the number of times the substring appears in the string.
The syntax is "substr_count(string,substring,start,length)
";
parameters respectively represent:
string is required, Specifies the string to be checked.
substring is required and specifies the string to be searched.
start is optional and specifies where to start searching in the string.
length is optional and specifies the length of the search.
PHP substr()
The function is used to return a part of the string. The return value is the extracted part of the returned string. If it fails, it returns FALSE, or returns an empty string. .
Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!
The above is the detailed content of How to find the first non-repeating character in a given string via PHP. For more information, please follow other related articles on the PHP Chinese website!