Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let’s discuss certain ways in which we can find the last occurrence of substring in string in Python.
Using rindex() to find last occurrence of substring
rindex() method returns the last occurrence of the substring if present in the string. The drawback of this function is that it throws the exception if there is no substring in the string and hence breaks the code.
Python3
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
print
(
"The original string : "
+
str
(test_string))
res
=
test_string.rindex(tar_word)
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Using rfind() to find last occurrence of substring
rfind() is the alternate method to perform this task. The advantage that this function offers better than the above method is that, this function returns a “-1” if a substring is not found rather than throwing the error.
Python3
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
print
(
"The original string : "
+
str
(test_string))
res
=
test_string.rfind(tar_word)
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Using lambda() with rlocate() function
Here we are using the more_itertools library that provides us with rlocate() function that helps us to find the last occurrence of the substring in the given string.
Python3
import
more_itertools as m
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
pred
=
lambda
*
x: x
=
=
tuple
(tar_word)
print
(
"The original string : "
+
str
(test_string))
res
=
next
(m.rlocate(test_string, pred
=
pred,
window_size
=
len
(tar_word)))
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output:
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Using find() and replace() methods
Python3
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
print
(
"The original string : "
+
str
(test_string))
x
=
test_string.count(tar_word)
i
=
1
while
(i<x):
test_string
=
test_string.replace(tar_word,
"*"
*
len
(tar_word),
1
)
i
+
=
1
res
=
test_string.find(tar_word)
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Time Complexity: O(n), where n is length of test_string.
Auxiliary Space: O(1)
Using the re module:
The re (regular expression) module in Python allows you to search for patterns in strings. In this approach, we use the finditer function from the re module to find all occurrences of the substring in the string. The finditer function returns an iterator yielding MatchObject instances that have information about the search, such as the start and end indices of the match.
We can then use a for loop to iterate through the matches and keep track of the index of the last occurrence by updating the last_occurrence variable whenever we find a match. Finally, we print the index of the last occurrence.
Python3
import
re
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
matches
=
re.finditer(tar_word, test_string)
last_occurrence
=
-
1
for
match
in
matches:
last_occurrence
=
match.start()
print
(
"Index of last occurrence of substring is:"
, last_occurrence)
Output
Index of last occurrence of substring is: 28
Time complexity: O(n), where n is the length of the string
Auxiliary Space : O(n)
Using reversed() function and index()
Step-by-step approach:
- Reverse the test_string and tar_word
- Use the index() method to get the first occurrence of the reversed tar_word in the reversed test_string.
- Calculate the index of the last occurrence of the tar_word by subtracting the index from the length of the test_string and the length of the tar_word.
Python3
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
res
=
len
(test_string)
-
test_string[::
-
1
].index(tar_word[::
-
1
])
-
len
(tar_word)
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output
Index of last occurrence of substring is : 28
Time complexity: O(n) where n is the length of the string
Space complexity: O(1)
Using the numpy:
Algorithm:
- Initialize the test string and target word.
- Create an empty numpy array to store the indices of all occurrences of the target word.
- Iterate over all possible substrings of length equal to the length of the target word in the test string. For each substring, check if it matches the target word or not. If the substring matches the target word, append the index of the first character of the substring to the numpy array.
- Check if any occurrences of the target word were found or not. If the numpy array is not empty, set the result to be the last element of the array (i.e., the index of the last occurrence of the target word in the test string). Otherwise, set the result to -1 (indicating that the target word was not found in the test string).
- Print the original string and the index of the last occurrence of the target word (or -1 if the target word was not found).
Below is the implementation of the above approach:
Python3
import
numpy as np
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
indices
=
np.array([i
for
i
in
range
(
len
(test_string)
-
len
(tar_word)
+
1
)
if
test_string[i:i
+
len
(tar_word)]
=
=
tar_word])
if
indices.size >
0
:
res
=
indices[
-
1
]
else
:
res
=
-
1
print
(
"The original string : "
+
str
(test_string))
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output:
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Time Complexity: O(n * m), where n is the length of the test string and m is the length of the target word. This is because the list comprehension iterates over all possible substrings of length m in the test string, which takes O(n * m) time in the worst case.
Space Complexity: O(k), where k is the number of occurrences of the target word in the test string. This is because the indices of all occurrences of the target word are stored in a numpy array, which takes O(k) space. The rest of the variables used in the code take constant space.
Using rpartition() method
- Define the string and target word to find last occurrence of substring.
- Use the rpartition() method to split the string at the last occurrence of the target word.
- If the length of split list is 1, print that the substring was not found in the string.
- Otherwise, calculate the index of the last occurrence of the target word using the length of the original string, the length of the third element in the split list (which contains the characters after the last occurrence of the target word), and the length of the target word.
- Print the index of the last occurrence of the target word.
Python3
test_string
=
"GfG is best for CS and also best for Learning"
tar_word
=
"best"
print
(
"The original string : "
+
str
(test_string))
split_list
=
test_string.rpartition(tar_word)
if
len
(split_list)
=
=
1
:
print
(
"Substring not found in string"
)
else
:
res
=
len
(test_string)
-
len
(split_list[
2
])
-
len
(tar_word)
print
(
"Index of last occurrence of substring is : "
+
str
(res))
Output
The original string : GfG is best for CS and also best for Learning Index of last occurrence of substring is : 28
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), as no extra is used.
Last Updated :
17 Apr, 2023
Like Article
Save Article
(PHP 4, PHP 5, PHP 7, PHP
strrpos — Возвращает позицию последнего вхождения подстроки в строке
Описание
strrpos(string $haystack
, string $needle
, int $offset
= 0): int|false
Список параметров
-
haystack
-
Строка, в которой производится поиск.
-
needle
-
До PHP 8.0.0, если параметр
needle
не является строкой,
он преобразуется в целое число и трактуется как код символа.
Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется.
В зависимости от предполагаемого поведения,
параметрneedle
должен быть либо явно приведён к строке,
либо должен быть выполнен явный вызов chr(). -
offset
-
Если равно или больше ноля, то поиск будет идти слева направо
и, при этом, будут пропущены первыеoffset
байт строкиhaystack
.Если меньше ноля, то поиск будет идти справа налево. При этом
будут отброшеныoffset
байт с конца
haystack
и найдено первое найденное
вхождениеneedle
.Замечание:
Фактически это будет последнее вхождение
needle
без учёта
offset
последних байт.
Возвращаемые значения
Возвращает номер позиции последнего вхождения needle
относительно начала строки haystack
(независимо от направления поиска и смещения (offset)).
Замечание:
Позиция в строке строки отсчитывается от 0, а не от 1.
Возвращает false
, если искомая строка не найдена.
Внимание
Эта функция может возвращать как логическое значение false
, так и значение не типа boolean, которое приводится к false
. За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Список изменений
Версия | Описание |
---|---|
8.0.0 |
Передача целого числа (int) в needle больше не поддерживается.
|
7.3.0 |
Передача целого числа (int) в needle объявлена устаревшей.
|
Примеры
Пример #1 Проверка существования искомой строки
Легко ошибиться и перепутать возвращаемые значения в случаях
«символ найден в нулевой позиции» и «символ не найден».
Вот так можно узнать разницу:
<?php
$pos
= strrpos($mystring, "b");
if ($pos === false) { // обратите внимание: три знака равенства
// не найдено...
}?>
Пример #2 Поиск со смещением
<?php
$foo = "0123456789a123456789b123456789c";var_dump(strrpos($foo, '7', -5)); // Поиск происходит в обратном направлении и
// начинается с пятой позиции с конца. Результат: int(17)var_dump(strrpos($foo, '7', 20)); // Начинает поиск с 20 позиции в строке.
// Результат: int(27)var_dump(strrpos($foo, '7', 28)); // Результат: bool(false)
?>
Результат выполнения данного примера:
int(0) bool(false) int(27) bool(false) int(17) bool(false) int(29)
Смотрите также
- strpos() — Возвращает позицию первого вхождения подстроки
- stripos() — Возвращает позицию первого вхождения подстроки без учёта регистра
- strripos() — Возвращает позицию последнего вхождения подстроки без учёта регистра
- strrchr() — Находит последнее вхождение символа в строке
- substr() — Возвращает подстроку
brian at enchanter dot net ¶
15 years ago
The documentation for 'offset' is misleading.
It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."
This is confusing if you think of strrpos as starting at the end of the string and working backwards.
A better way to think of offset is:
- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).
- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.
If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:
strrpos($text, " ", -(strlen($text) - 50));
If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
david dot mann at djmann dot co dot uk ¶
5 years ago
Ten years on, Brian's note is still a good overview of how offsets work, but a shorter and simpler summary is:
strrpos($x, $y, 50); // 1: this tells strrpos() when to STOP, counting from the START of $x
strrpos($x, $y, -50); // 2: this tells strrpos() when to START, counting from the END of $x
Or to put it another way, a positive number lets you search the rightmost section of the string, while a negative number lets you search the leftmost section of the string.
Both these variations are useful, but picking the wrong one can cause some highly confusing results!
dave at pixelmetrics dot com ¶
3 years ago
The description of offset is wrong. Here’s how it works, with supporting examples.
Offset effects both the starting point and stopping point of the search. The direction is always right to left. (The description wrongly says PHP searches left to right when offset is positive.)
Here’s how it works:
When offset is positive, PHP searches right to left from the end of haystack to offset. This ignores the left side of haystack.
When offset is negative, PHP searches right to left, starting offset bytes from the end, to the start of haystack. This ignores the right side of haystack.
Example 1:
$foo = ‘aaaaaaaaaa’;
var_dump(strrpos($foo, 'a', 5));
Result: int(10)
Example 2:
$foo = "aaaaaa67890";
var_dump(strrpos($foo, 'a', 5));
Result: int(5)
Conclusion: When offset is positive, PHP searches right to left from the end of haystack.
Example 3:
$foo = "aaaaa567890";
var_dump(strrpos($foo, 'a', 5));
Result: bool(false)
Conclusion: When offset is positive, PHP stops searching at offset.
Example 4:
$foo = ‘aaaaaaaaaa’;
var_dump(strrpos($foo, 'a', -5));
Result: int(6)
Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end.
Example 5:
$foo = "a234567890";
var_dump(strrpos($foo, 'a', -5));
Result: int(0)
Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.
Daniel Brinca ¶
15 years ago
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):
//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
$size = strlen ($haystack);
$pos = strpos (strrev($haystack), $needle, $size - $offset);
if ($pos === false)
return false;
return $size - $pos;
}
Note: supports full strings as needle
anonymous ¶
2 years ago
There is a lot of confusion around how $offset works and I feel it's really quite simple.
If $offset is positive, the operation ignores the first $offset characters of the haystack.
If $offset is negative, the operation ignores the last $offset-1 characters of the haystack (don't ask why -1...).
To understand this instinctively, just imagine the characters being replaced with invalid symbols. Here's an example:
<?php
$hackstack = '0123456789';// Search the entire sequence 0123456789
var_dump(strrpos($hackstack, '0')); // int(0)
var_dump(strrpos($hackstack, '9')); // int(9)
// Only search ##23456789
var_dump(strrpos($hackstack, '1', 2)); // bool(false)
var_dump(strrpos($hackstack, '2', 2)); // int(2)
// Only search 0123456###
var_dump(strrpos($hackstack, '6', -4)); // int(6)
var_dump(strrpos($hackstack, '7', -4)); // bool(false)?>
dmitry dot polushkin at gmail dot com ¶
16 years ago
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
<?php
function filename_extension($filename) {
$pos = strrpos($filename, '.');
if($pos===false) {
return false;
} else {
return substr($filename, $pos+1);
}
}
?>
escii at hotmail dot com ( Brendan ) ¶
18 years ago
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.
<?
function proper_strrpos($haystack,$needle){
while($ret = strrpos($haystack,$needle))
{
if(strncmp(substr($haystack,$ret,strlen($needle)),
$needle,strlen($needle)) == 0 )
return $ret;
$haystack = substr($haystack,0,$ret -1 );
}
return $ret;
}
?>
fab ¶
17 years ago
RE: hao2lian
There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.
<?phpfunction my_strrpos($haystack, $needle) {
$index = strpos(strrev($haystack), strrev($needle));
if($index === false) {
return false;
}
$index = strlen($haystack) - strlen($needle) - $index;
return $index;
}?>
arlaud pierre ¶
10 years ago
This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.
<?php
function strrpos_handmade($haystack, $needle, $offset = 0){
if(
$offset === 0) return strrpos($haystack, $needle);$length = strlen($haystack);
$size = strlen($needle);
if(
$offset < 0) {
$virtual_cut = $length+$offset;
$haystack = substr($haystack, 0, $virtual_cut+$size);
$ret = strrpos($haystack, $needle);
return $ret > $virtual_cut ? false : $ret;
} else {
$haystack = substr($haystack, $offset);
$ret = strrpos($haystack, $needle);
return $ret === false ? $ret : $ret+$offset;
}
}
?>
shimon at schoolportal dot co dot il ¶
17 years ago
In strrstr function in php 4 there is also no offset.
<?
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
$needle=$needle[0];
$l=strlen($haystack);
if($l==0) return false;
if($offset===false) $offset=$l-1;
else
{
if($offset>$l) $offset=$l-1;
if($offset<0) return false;
}
for(;$offset>0;$offset--)
if($haystack[$offset]==$needle)
return $offset;
return false;
}
?>
islandispeace at hotmail dot com ¶
7 years ago
$offset is very misleading, here is my understanding:
function mystrrpos($haystack, $needle, $offset = 0) {
if ($offset == 0) {
return strrpos ($haystack, $needle);
} else {
return strrpos (substr($haystack, 0, $offset), $needle);
}
}
gordon at kanazawa-gu dot ac dot jp ¶
17 years ago
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:
function my_strrpos($haystack, $needle, $offset=0) {
// same as strrpos, except $needle can be a string
$strrpos = false;
if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
$strlen = strlen($haystack);
$strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
if (is_numeric($strpos)) {
$strrpos = $strlen - $strpos - strlen($needle);
}
}
return $strrpos;
}
alexandre at NOSPAM dot pixeline dot be ¶
14 years ago
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.
This did the trick:
<?php
// Detect and remove a trailing slash
$root_folder = ((strrpos($root_folder, '/') + 1) == strlen($root_folder)) ? substr($root_folder, 0, - 1) : $root_folder;
?>
su.noseelg@naes, only backwards ¶
20 years ago
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:
The quick brown fox jumps over the lazy
dog.
So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with ' '.
<?php
function no_orphans($TheParagraph) {
if (substr_count($TheParagraph," ") > 1) {
$lastspace = strrpos($TheParagraph," ");
$TheParagraph = substr_replace($TheParagraph," ",$lastspace,1);
}
return $TheParagraph;
}
?>
So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy dog." That way, the last two words will always stay together.
maxmike at gmail dot com ¶
13 years ago
I've got a simple method of performing a reverse strpos which may be of use. This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.
Here is an example of backwards stepping through instances of a string with this function:
<?php
function backwardStrpos($haystack, $needle, $offset = 0){
$length = strlen($haystack);
$offset = ($offset > 0)?($length - $offset):abs($offset);
$pos = strpos(strrev($haystack), strrev($needle), $offset);
return ($pos === false)?false:( $length - $pos - strlen($needle) );
}$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
echo $pos."<br/>";
$pos--;
if($pos < 0){
echo "Done<br/>";break;
}
}
echo "---===---<br/>nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>
Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4
With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)
The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).
This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
FIE ¶
20 years ago
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:
<?php
function strlpos($f_haystack,$f_needle) {
$rev_str = strrev($f_needle);
$rev_hay = strrev($f_haystack);
$hay_len = strlen($f_haystack);
$ned_pos = strpos($rev_hay,$rev_str);
$result = $hay_len - $ned_pos - strlen($rev_str);
return $result;
}
?>
this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).
~SILENT WIND OF DOOM WOOSH!
jafet at g dot m dot a dot i dot l dot com ¶
16 years ago
Full strpos() functionality, by yours truly.
<?php
function conforming_strrpos($haystack, $needle, $offset = 0)
{
# Why does strpos() do this? Anyway...
if(!is_string($needle)) $needle = ord(intval($needle));
$haystack = strval($haystack);
# Parameters
$hlen = strlen($haystack);
$nlen = strlen($needle);
# Come on, this is a feature too
if($nlen == 0)
{
trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
return false;
}
$offset = intval($offset);
$hrev = strrev($haystack);
$nrev = strrev($needle);
# Search
$pos = strpos($hrev, $nrev, $offset);
if($pos === false) return false;
else return $hlen - $nlen - $pos;
}
?>
Note that $offset is evaluated from the end of the string.
Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
dixonmd at gmail dot com ¶
15 years ago
<?php
$pos = strlen(string $haystack) - strpos (strrev(string $haystack), strrev(string $needle)) - strlen(string $needle);
?>
If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.
eg :
<?php
$haystack = "you you you you you";
$needle = "you";
$pos1 = strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
echo $pos1 . "<br>";
$pos2 strrpos($haystack, $needle);
echo $pos2 . "<br>";
?>
kavih7 at yahoo dot com ¶
16 years ago
<?php
###################################################
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################
function strrpos_string($haystack, $needle, $offset = 0)
{
if(trim($haystack) != "" && trim($needle) != "" && $offset <= strlen($haystack))
{
$last_pos = $offset;
$found = false;
while(($curr_pos = strpos($haystack, $needle, $last_pos)) !== false)
{
$found = true;
$last_pos = $curr_pos + 1;
}
if($found)
{
return $last_pos - 1;
}
else
{
return false;
}
}
else
{
return false;
}
}
?>
stevewa ¶
6 years ago
i wanted to find a leading space BEFORE a hyphen
Crude Oil (Dec) 51.00-56.00
so I had to find the position of the hyphen
then subtract that position from the length of the string (to make it a negative number)
and then walk left toward the beginning of the string, looking for the first space before the hyphen
ex:
$str_position_hyphen = strpos($line_new,"-",$str_position_spread);
$line_new_length = strlen($line_new);
$str_position_hyphen_from_end = $str_position_hyphen - $line_new_length;
echo "hyphen position from end = " . $str_position_hyphen_from_end . "<br />n";
$str_position_space_before_hyphen = strrpos($line_new, " ", $str_position_hyphen_from_end);
echo "*** previous space= " . $str_position_space_before_hyphen . "<br />n";
$line_new = substr_replace($line_new, ",", $str_position_space_before_hyphen, 1 );
echo $line_new . "<br /><br />n";
lee at 5ss dot net ¶
19 years ago
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters. This is a recursive function. I have not tested to see if it is more or less efficient than the others on the page. I hope this helps someone!
<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
$tempPos = strpos($haystack, $needle, $start);
if($tempPos === false){
if($start == 0){
//Needle not in string at all
return false;
}else{
//No more occurances found
return $start - strlen($needle);
}
}else{
//Find the next occurance
return str_rpos($haystack, $needle, $tempPos + strlen($needle));
}
}
?>
Christ Off ¶
16 years ago
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found
function TruncateString($phrase, $longueurMax = 150) {
$phrase = substr(trim($phrase), 0, $longueurMax);
$pos = strrpos($phrase, " ");
$phrase = substr($phrase, 0, $pos);
if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
$phrase = substr($phrase,0,-1);
}
if ($pos === false) {
$phrase = $phrase;
}
else {
$phrase = $phrase . "...";
}
return $phrase;
}
jonas at jonasbjork dot net ¶
18 years ago
I needed to remove last directory from an path, and came up with this solution:
<?php
$path_dir
= "/my/sweet/home/";
$path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
echo $path_up;?>
Might be helpful for someone..
griffioen at justdesign dot nl ¶
18 years ago
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:
function lastIndexOf($haystack, $needle) {
$index = strpos(strrev($haystack), strrev($needle));
$index = strlen($haystack) - strlen(index) - $index;
return $index;
}
nexman at playoutloud dot net ¶
18 years ago
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.
function strepos($haystack, $needle, $offset=0) {
$pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
$last_pos = false; $first_run = true;
do {
$pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
$last_pos = $pos;
} else { break; }
$first_run = false;
} while ($pos !== false);
if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
return $last_pos;
}
If my math is off, please feel free to correct.
- A positive offset will be the minimum character index position of the first character allowed.
- A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.
returns the character index ( 0+ ) of the last occurence of the needle.
* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
php dot net at insite-out dot com ¶
20 years ago
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:
<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_index_of($sub_str,$instr) {
if(strstr($instr,$sub_str)!="") {
return(strlen($instr)-strpos(strrev($instr),$sub_str));
}
return(-1);
}
?>
It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
php NO at SPAMMERS willfris SREMMAPS dot ON nl ¶
16 years ago
<?php
/*******
** Maybe the shortest code to find the last occurence of a string, even in php4
*******/
function stringrpos($haystack,$needle,$offset=NULL)
{
return strlen($haystack)
- strpos( strrev($haystack) , strrev($needle) , $offset)
- strlen($needle);
}
// @return -> chopped up for readability.
?>
ZaraWebFX ¶
19 years ago
this could be, what derek mentioned:
<?
function cut_last_occurence($string,$cut_off) {
return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}
// example: cut off the last occurence of "limit"
$str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
$search = " limit";
echo $str."n";
echo cut_last_occurence($str,"limit");
?>
mijsoot_at_gmail_dot_com ¶
16 years ago
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.
$return_context = "1173120681_0__0_0_Mijsoot_Thierry";
// Here i need to find = "Mijsoot_Thierry"
//echo $return_context."<br />";// -- DEBUG
function findPos($haystack,$needle,$position){
$pos = strrpos($haystack, $needle);
if($position>1){
$position --;
$haystack = substr($haystack, 0, $pos);
$pos = findPos($haystack,$needle,$position);
}else{
// echo $haystack."<br />"; // -- DEBUG
return $pos;
}
return $pos;
}
var_dump(findPos($return_context,"_",2)); // -- TEST
genetically altered mastermind at gmail ¶
17 years ago
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
tsa at medicine dot wisc dot edu ¶
19 years ago
What the heck, I thought I'd throw another function in the mix. It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:
<?php
function strrposmixed ($haystack, $needle, $start=0) {
// init start as the end of the str if not set
if($start == 0) {
$start = strlen($haystack);
}
// searches backward from $start
$currentStrPos=$start;
$lastFoundPos=false;
while(
$currentStrPos != 0) {
if(!(strpos($haystack,$needle,$currentStrPos) === false)) {
$lastFoundPos=strpos($haystack,$needle,$currentStrPos);
break;
}
$currentStrPos--;
}
if(
$lastFoundPos === false) {
return false;
} else {
return $lastFoundPos;
}
}
?>
info at qrworld dot net ¶
8 years ago
pb at tdcspace dot dk ¶
15 years ago
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....
ex: find 'Z' in $str from position $p, backward...
while($p > -1 and $str{$p} <> 'Z') $p--;
Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
purpleidea ¶
16 years ago
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.
tremblay dot jf at gmail dot com ¶
9 years ago
I created an easy function that search a substring inside a string.
It reverse the string and the substring inside an strpos and substract the result to the length of the string.
if (!function_exists("real_strrpos")) {
function real_strrpos($haystack,$needle) {
$pos = strlen($haystack);
$pos -= strpos(strrev($haystack), strrev($needle) );
$pos -= strlen($needle);
return $pos;
}
}
Обзор PHP-функций для работы со строками и практическое их применение с учетом кодировки UTF-8.
1
Количество символов
Получить длину строки
Функция strlen($string) возвращает длину строки, но возвращает неправильный результат если в строке есть кириллица в UTF-8, поэтому нужно использовать mb_strlen()
.
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo strlen($text); // 105
echo mb_strlen($text); // 59
PHP
Количество символов без пробелов
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_ereg_replace('[s]', '', $text);
echo mb_strlen($str); // 49
PHP
Количество слов с строке
Функция str_word_count() возвращает количество слов в строке, но символы обрамленные пробелами будет считаться за слово, например « — ». Так же функция не работает с UTF-8, как видно в примере:
$text = 'Lorem Ipsum - is simply dummy!';
echo str_word_count($text); // 6
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo str_word_count($text); // 1
PHP
Рабочий вариант:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace("/[[:punct:]]/", '', $text);
$str = mb_ereg_replace('[s]+', ' ', $str);
$words = explode(' ', $str);
echo count($words); // 10
PHP
Получить количество переносов в строке
$text = 'Съешь ещё - этих
мягких французских булок,
да выпей же чаю.';
echo substr_count($text, PHP_EOL); // 2
PHP
Количество букв в строке
$text = 'Съешь ещё этих мягких французских булок, да выпей же чаю.';
echo $str = preg_replace('/[^a-zа-яё]/ui', '', $text);
echo mb_strlen($str); // 46
PHP
Количество цифр в строке
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace('/[^0-9]/ui', '', $text);
echo mb_strlen($str); // 0
PHP
Количество знаков препинания
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = preg_replace("/[^[:punct:]]/", '', $text);
echo mb_strlen($str); // 3
PHP
Количество пробелов в строке
Или количество вхождений любого другого символа или подстроки.
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo substr_count($text, ' '); // 10
PHP
Количество пробелов в начале строки:
$text = ' Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strlen($text) - mb_strlen(ltrim($text, ' ')); // 5
PHP
Количество пробелов в конце строки:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю. ';
echo mb_strlen($text) - mb_strlen(rtrim($text, ' ')); // 3
PHP
2
Поиск
Получить количество вхождений подстроки
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_substr_count($text, 'ещё'); // 2
PHP
Найти позицию первого вхождения подстроки
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strpos($text, 'ещё'); // 6
// Без учета регистра:
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_stripos($text, 'ещё'); // 6
PHP
Найти позицию последнего вхождения подстроки
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strrpos($text, 'ещё'); // 46
// Без учета регистра:
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
echo mb_strirpos($text, 'ещё'); // 46
PHP
Найти все вхождения подстроки
$text = 'Съешь ещё - этих мягких французских булок, да ещё выпей же чаю.';
$offset = 0;
$allpos = array();
while (($pos = mb_strpos($text, 'ещё', $offset)) !== false) {
$offset = $pos + 1;
$allpos[] = $pos;
}
print_r($allpos); // Array ([0] => 6 [1] => 46)
PHP
3
Извлечение из текста
Начало строки
Получить первый символ:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, 1); // С
PHP
Получить три первых символа:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, 3); // Съе
PHP
Получить первое слово:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strstr($text, ' ', true); // Съешь
PHP
Получить все после первого слова:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_strstr($text, ' ', false); // ещё - этих мягких французских булок, да выпей же чаю.
PHP
Конец строки
Получить последний символ:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, -1, 1); // .
PHP
Получить три последних символа:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, -1, 3); // аю.
PHP
Получить последнее слово:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$array = explode(' ', $text);
echo end($array); // чаю.
PHP
Получить всё до последнего слова:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_substr($text, 0, mb_strrpos($text, ' '));
echo $str; // Съешь ещё - этих мягких французских булок, да выпей же
PHP
Середина строки
Получить второе слово:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$array = explode(' ', $text);
echo $array[1]; // ещё
PHP
Получить текст до дефиса:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
echo mb_substr($text, 0, mb_strpos($text, ' - ')); // Съешь ещё
PHP
Получить текст после дефиса:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$str = mb_substr($text, mb_strpos($text, ' - ') + mb_strlen(' - '), -1);
echo $str; // этих мягких французских булок, да выпей же чаю
PHP
Переносы строк
Получить первую строку:
$text = 'Разнообразный опыт укрепление и развитие структуры требуют
определения направлений прогрессивного развития! Не следует забывать,
что постоянный рост и сфера активности в степени обуславливает создание
системы обучения кадров? С другой стороны дальнейшее развитие различных
форм влечет за собой процесс внедрения и модернизации.';
$pos = mb_strpos($text, "n");
$str = trim(mb_substr($text, 0, $pos));
echo $str; // Разнообразный опыт укрепление и развитие структуры требуют
// или
$lines = explode("n", $text);
echo $lines[0]; // Разнообразный опыт укрепление и развитие структуры требуют
PHP
Получить последнюю строку:
$text = 'Разнообразный опыт укрепление и развитие структуры требуют
определения направлений прогрессивного развития! Не следует забывать,
что постоянный рост и сфера активности в степени обуславливает создание
системы обучения кадров? С другой стороны дальнейшее развитие различных
форм влечет за собой процесс внедрения и модернизации.';
$pos = mb_strrpos($text, "n");
$str = trim(mb_substr($text, $pos));
echo $str; // форм влечет за собой процесс внедрения и модернизации.
// или
$lines = explode("n", $text);
echo end($lines); // форм влечет за собой процесс внедрения и модернизации.
PHP
Пилучить символы из ковычек и скобок
$text = ''Съешь' "ещё" «этих» [мягких] (французских) {булок} <да>';
// '...'
preg_match_all("/'(.+?)'/", $text, $matches);
echo $matches[1][0]; // Съешь
// "..."
preg_match_all("/"(.+?)"/", $text, $matches);
echo $matches[1][0]; // ещё
// «...»
preg_match_all("/«(.+?)»/", $text, $matches);
echo $matches[1][0]; // этих
// [...]
preg_match_all("/[(.+?)]/", $text, $matches);
echo $matches[1][0]; // мягких
// (...)
preg_match_all("/((.+?))/", $text, $matches);
echo $matches[1][0]; // французских
// {...}
preg_match_all("/{(.+?)}/", $text, $matches);
echo $matches[1][0]; // булок
// <...>
preg_match_all("/<(.+?)>/", $text, $matches);
echo $matches[1][0]; // да
PHP
4
Замена в строках
Функция substr_replace($search, $replace, $subject, $count) – заменяет часть строки, также не раотает с кирилицей в кодировке UTF-8, в библиатеке mb_string её нет, поэтому приходится использовать пользовольскую функцию:
if (!function_exists('mb_substr_replace')) {
function mb_substr_replace($original, $replacement, $position, $length)
{
$startString = mb_substr($original, 0, $position, 'UTF-8');
$endString = mb_substr($original, $position + $length, mb_strlen($original), 'UTF-8');
$out = $startString . $replacement . $endString;
return $out;
}
}
PHP
Заменить первый символ:
$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!', 0, 1); // !ъешь ещё - этих мягких французских булок.
PHP
Заменить три первых символа:
$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!!!', 0, 3); // !!!шь ещё - этих мягких французских булок.
PHP
Заменить последний символ:
$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!', -1, 0); // Съешь ещё - этих мягких французских булок!
PHP
Заменить три последних символа:
$text = 'Съешь ещё - этих мягких французских булок.';
echo mb_substr_replace($text, '!!!', -3, 0); // Съешь ещё - этих мягких французских бул!!!
PHP
Замена символов и слов в строке
Для этой задачи подходит функция str_replace($search, $replace, $subject), которая работает со всеми кодировками.
Заменить пробелы:
$text = 'Съешь ещё - этих мягких французских булок.';
echo str_replace(' ', '-', $text); // Съешь-ещё---этих-мягких-французских-булок.
PHP
Заменить слово:
$text = 'Съешь ещё - этих мягких французских булок.';
echo str_replace('мягких', 'твердых', $text); // Съешь ещё - этих твердых французских булок.
PHP
Заменить всё до дефиса:
$text = 'Съешь ещё - этих мягких французских булок.';
$str = 'Не ешь' . mb_substr($text, mb_strpos($text, ' - '), -1);
echo $str; // Не ешь - этих мягких французских булок
PHP
Заменить всё после дефиса:
$text = 'Съешь ещё - этих мягких французских булок.';
$str = mb_substr($text, 0, mb_strpos($text, ' - ') + 3) . 'печенек';
echo $str; // Съешь ещё - печенек
PHP
5
Добавление в строки
Добавить строку после 10-го символа:
$text = 'Съешь ещё - этих мягких французских булок.';
$str = mb_substr_replace($text, '!!!', 10, 0);
echo $str; // Съешь ещё !!!- этих мягких французских булок.
PHP
Добавить перед словом:
$text = 'Съешь ещё - этих мягких французских булок.';
$str = str_replace(' ещё ', ' же ещё ', $text);
echo $str; // Съешь же ещё - этих мягких французских булок.
PHP
Добавить после слова:
$text = 'Съешь ещё - этих мягких французских булок.';
$str = str_replace(' ещё ', ' ещё немного ', $text);
echo $str; // Съешь ещё немного - этих мягких французских булок.
PHP
Вставить строку между всех символов
Для того чтобы вставить символ между всех символов в строке понадобится функция str_split($string) для пробразавания строки в массив, она также не работает с кирилицей. С версии PHP 7.4 появилась функция mb_str_split()
, для более ранних версий:
if (!function_exists('mb_str_split')) {
function mb_str_split($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
}
PHP
$text = 'Съешь ещё - этих мягких французских булок.';
$array = mb_str_split($text);;
$new = implode(' ', $array);
echo $new; // С ъ е ш ь е щ ё - э т и х м я г к и х ф р а н ц у з с к и х б у л о к .
PHP
Дописать строку до нужной длины
Функция str_pad($string, $length, $pad_string, $pad_type) дополняет строку другой строкой до заданной длины.
Версия функции для UTF-8:
if (!function_exists('mb_str_pad')) {
function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT)
{
$diff = strlen($input) - mb_strlen($input);
return str_pad($input, $pad_length + $diff, $pad_string, $pad_type);
}
}
PHP
Дописать стркуку слева:
$text = 'Привет Мир';
echo mb_str_pad($text, 20, '-', STR_PAD_LEFT); // ----------Привет Мир
PHP
Дописать строку справа:
$text = 'Привет Мир';
echo mb_str_pad($text, 20, '-', STR_PAD_RIGHT); // Привет Мир----------
PHP
Дописать строку с обеих сторон:
$text = 'Привет Мир';
echo mb_str_pad($text, 20, '-', STR_PAD_BOTH); // -----Привет Мир-----
PHP
6
Удаление из строк
Удаление в начале строки
Удалить первый символ:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 1);
echo $new; // ъешь ещё - этих мягких французских булок, да выпей же чаю.
PHP
Удалить первые 3 символа:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 3);
echo $new; // шь ещё - этих мягких французских булок, да выпей же чаю.
PHP
Удалить первое слово:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, mb_strpos($text, ' '));
echo $new; // ещё - этих мягких французских булок, да выпей же чаю.
PHP
Удаление в конце строки
Удалить последний символ:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, -1);
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же чаю
PHP
Удалить три последних символа:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, -3);
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же ч
PHP
Удалить последнее слово:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = mb_substr($text, 0, mb_strrpos($text, ' '));
echo $new; // Съешь ещё - этих мягких французских булок, да выпей же
PHP
Удаление подсторк
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = str_replace(' мягких', '', $text);
echo $new; // Съешь ещё - этих французских булок, да выпей же чаю.
PHP
Удалить всё перед сиволом:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = strstr($text, '-');
echo $new; // - этих мягких французских булок, да выпей же чаю.
PHP
Удалить всё после сивола:
$text = 'Съешь ещё - этих мягких французских булок, да выпей же чаю.';
$new = strstr($text, '-', true);
echo $new; // Съешь ещё
// Второй вариант:
$pos = mb_strpos($text, '-');
$new = mb_substr($text, 0, $pos + 1);
echo $new; // Съешь ещё -
PHP
Содержание
- Основные методы работы со строками в C#
- Сравнение строк в C#
- Сравнение строк в C# без учёта региональных настроек
- Проверка вхождения подстроки в строку в C#
- Объединение строк в C# (конкатенация строк)
- Объединение строк с использованием разделителя в C#
- Копирование строк в C#
- Проверка совпадения строк в C#
- Форматирование строк в C#
- Поиск в строках C#
- Вставка подстроки в строку C#
- Замена символов и подстрок в строках C#
- Разделение строк на подстроки в C#
- Извлечение подстрок из строки в C#
- Изменение регистра строк в C#
- Обрезка строк в C#
- Итого
уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.
В предыдущей статье мы рассмотрели основные моменты, касающиеся работы со строками в C#: создание строк, неизменность строк, использование регулярных и буквальных литералов в строках и так далее. Сегодня мы продолжим разбираться с этой важной и довольно интересной темой и рассмотрим основные методы работы со строками в C#.
Функциональность класса System.String
наиболее полно раскрывается через его методы, основными из которых являются следующие:
Compare
— сравнивает две строки с учетом текущих региональных настроек (локали) пользователяCompareOrdinal
— сравнивает две строки без учета локалиContains
— проверяет, содержится ли заданная подстрока в строкеConcat
— объединяет строкиCopyTo
— копирует часть строки, начиная с определенного индекса, в массивEndsWith
— проверяет совпадает ли конец строки с подстрокойFormat
— форматирует строкуIndexOf
— находит индекс первого вхождения символа или подстроки в строкеInsert
— вставляет в строку подстрокуJoin
— соединяет элементы массива строкLastIndexOf
— находит индекс последнего вхождения символа или подстроки в строкеReplace
— заменяет в строке символ или подстроку другим символом или подстрокойSplit
— разделяет одну строку на массив строкSubstring
— извлекает из строки подстроку, начиная с указанной позицииToLower
— переводит все символы строки в нижний регистрToUpper
— переводит все символы строки в верхний регистрTrim
— удаляет начальные и конечные пробелы из строки
Рассмотрим представленные методы более подробно.
Сравнение строк в C#
Для сравнения двух строк в C# удобно использовать метод Compare
.
public static int Compare (string strA, string strB);
Результатом выполнения метода является целое число Int32. Это число означает следующее:
Результат Compare |
Что означает |
Меньше нуля | strA предшествует strB в порядке сортировки (стока strA меньше строки strB ). |
Нуль | strA занимает ту же позицию в порядке сортировки, что и объект strB (строки равны) |
Больше нуля | strA следует за strB в порядке сортировки (стока strA больше строки strB ). |
Например,
string s1 = "Строка"; string s2 = "Строка"; int res = string.Compare(s1, s2); Console.WriteLine(res);
Вернет значение 0
так как строки равны.
У класса String
есть также несколько перегруженных методов Compare
, позволяющих провести настройку способа сравнения строк. Например, можно сравнивать строки, игнорируя регистр:
public static int Compare(String? strA, String? strB, bool ignoreCase);
или определить свои настройки сравнения строк, используя следующий вариант метода Compare
:
public static int Compare(String? strA, String? strB, StringComparison comparisonType);
Несмотря на то, что метод Compare по умолчанию предназначен для сравнения строк с учётом локали, используя перегруженные версии метода, можно сравнивать строки и без учёта региональных настроек, например, воспользовавшись вот таким способом:
string.Compare(s1, s2, true, System.Globalization.CultureInfo.InvariantCulture);
Сравнение строк в C# без учёта региональных настроек
Метод CompareOrdinal
сравнивает два объекта String
, оценивая числовые значения соответствующих объектов Char
в каждой строке. Результат выполнения метода такой же, как и у предыдущего метода Compare (см. таблицу выше).
Проверка вхождения подстроки в строку в C#
Метод Contains
проверяет, входит ли заданная подстрока в строку. Этот метод не статический, поэтому использовать его необходимо только после создания объекта, то есть следующим образом:
string s1 = "Строка"; string s2 = "ока"; if (s1.Contains(s2)) { Console.WriteLine($"Строка {s1} содержит подстроку {s2}"); } else { Console.WriteLine($"Строка {s1} не содержит подстроку {s2}"); }
В примере выше мы проверяем содержится ли подстрока "ока"
в строке "Строка"
. Очевидно, что результатом выполнения метода будет true
.
Объединение строк в C# (конкатенация строк)
Для объединения строк в C# удобно использовать метод Concat
. Этот метод принимает два или более параметров, позволяя объединять не только строки, но и строковые представления любых объектов. Например:
string s1 = "Hello"; string s2 = " world"; string s3 = string.Concat(s1, s2); Console.WriteLine(s3);
Также возможно объединять и массивы строк:
string[] strArr = new string[3] { "Это", "массив", "строк" }; string s4 = string.Concat(strArr); Console.WriteLine(s4);
Объединение строк с использованием разделителя в C#
Для того, чтобы объединить несколько строк с использованием заданного разделителе, в C# используется метод Join
. В качестве входных параметров метод Join
принимает массив или коллекцию строк и символ-разделитель, например:
string[] strArr = new string[3] { "Это", "массив", "строк" }; string s5 = string.Join('|', strArr); Console.WriteLine(s5);
Для приведенного выше примера в консоли мы получим следующую объединенную строку:
Копирование строк в C#
Для копирования строк в C# можно воспользоваться не статическим методом CopyTo
. Этот метод копирует из строки часть символов, начиная с заданной позиции, и вставляет их в массив символов, также с указанной позиции. Сигнатура метода следующая:
(int sourceIndex, char[] destination, int destinationIndex, int count);
Для того, чтобы продемонстрировать работу метода, воспользуемся следующим примером:
char[] charArr = new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; string s6 = "string"; s6.CopyTo(2, charArr, 0, 4); Console.WriteLine(charArr);
в результате выполнения мы получим следующий вывод в консоли:
В этом примере из строки s6
копируется 4
символа, начиная с символа с индексом 2
(так как нумерация начинается с нуля, то первый копируемый символ r
) и вставляется в массив charArr
, начиная с первого элемента (с индексом 0
)
Также можно воспользоваться статическим методом Copy
для создания полной копии строки:
string s6 = "string"; string s7 = string.Copy(s6); Console.WriteLine(s7);
Проверка совпадения строк в C#
Достаточно часто при работе со строками приходится проверять вхождение одной подстроки в другую. Для выполнения проверки совпадения строк и подстрок в C# можно воспользоваться двумя методами:
public bool EndsWith(String value); public bool StartsWith(String value);
Первый метод (EndWith
) проверяет заканчивается ли проверяемая строка подстрокой value
, а второй, соответственно, проводит проверку на наличие подстроки value
в начале строки. Оба метода имеют перегрузки. Пример:
string s6 = "string"; if (s6.StartsWith("str")) Console.WriteLine("Найдено совпадение подстроки "str" в начале строки"); if (s6.EndsWith("ing")) Console.WriteLine("Найдено совпадение подстроки "ing" в конце строки");
Форматирование строк в C#
Помимо использования регулярных и буквальных литералов при работе со строками, мы также можем создавать строки в C# используя метод Format
. Для того, чтобы раскрыть все возможности форматирования строк, думаю, что потребуется написать отдельную статью. Сейчас же я просто продемонстрирую некоторые основные возможности использования этого метода.
double value = 7.123456789; double value2 = 7.12; string s8 = string.Format("Строка для форматирования. Первое число {0}, второе число {1}", value, value2); Console.WriteLine(s8);
Результатом будет следующая строка:
Строка для форматирования. Первое число 7,123456789, второе число 7,12
Поиск в строках C#
Ещё одной частой задачей при работе со строками в C# является поиск символов и подстрок в строках. Поиск в строке можно осуществить, в том числе, с использованием метода IndexOf
, имеющего несколько перегрузок:
public int IndexOf(String value, StringComparison comparisonType); public int IndexOf(String value, int startIndex, StringComparison comparisonType); public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType); public int IndexOf(String value, int startIndex, int count); public int IndexOf(String value); public int IndexOf(char value, StringComparison comparisonType); public int IndexOf(char value, int startIndex, int count); public int IndexOf(char value, int startIndex); public int IndexOf(char value);
Этот метод возвращает индекс первого вхождения указанного символа или подстроки в строку. Например,
string s9 = "Строка для поиска символов и подстрок"; int index = s9.IndexOf("о"); if (index > -1) Console.WriteLine("Индекс первого вхождения символа в строку {0}", index); index = s9.IndexOf("сим"); if (index > -1) Console.WriteLine("Индекс первого символа искомой подстроки {0}", index);
Результатом выполнения будут следующие строки в консоли:
Индекс первого вхождения символа в строку 3
Индекс первого символа искомой подстроки 18
Соответственно, чтобы найти последнее вхождение символа или подстроки в строку, достаточно воспользоваться методом:
public int LastIndexOf(char value, int startIndex, int count); public int LastIndexOf(char value, int startIndex); public int LastIndexOf(String value, StringComparison comparisonType); public int LastIndexOf(String value, int startIndex, StringComparison comparisonType); public int LastIndexOf(char value); public int LastIndexOf(String value, int startIndex, int count); public int LastIndexOf(String value, int startIndex); public int LastIndexOf(String value); public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType);
Вставка подстроки в строку C#
Для вставки одной строки в другую в C# можно воспользоваться методом Insert
:
public String Insert(int startIndex, String value);
Этот метод вставляет в строку, начиная с индекса startIndex
подстроку value
и возвращает в результате новый экземпляр строки. Например,
string s10 = "Hello "; string s11 = s10.Insert(6, "world"); Console.WriteLine(s11);
Результат
Замена символов и подстрок в строках C#
Для замены символов и подстрок в строках C# используется метод Replace:
public String Replace(char oldChar, char newChar); public String Replace(String oldValue, String? newValue); public String Replace(String oldValue, String? newValue, bool ignoreCase, CultureInfo? culture); public String Replace(String oldValue, String? newValue, StringComparison comparisonType);
Например, заменим все символы o
с строке на символы А
:
string s12 = "Исходная строка для замены всех символов о на символы А"; string s13 = s12.Replace('о', 'А'); Console.WriteLine(s13);
Результат
ИсхАдная стрАка для замены всех симвАлАв А на симвАлы А
Разделение строк на подстроки в C#
Разделение строк на подстроки в C# также является достаточно частой задачей в программировании. Для этого можно воспользоваться методом Split
public String[] Split(String[]? separator, int count, StringSplitOptions options); public String[] Split(String? separator, int count, StringSplitOptions options = StringSplitOptions.None); public String[] Split(String[]? separator, StringSplitOptions options); public String[] Split(char[]? separator, int count, StringSplitOptions options); public String[] Split(String? separator, StringSplitOptions options = StringSplitOptions.None); public String[] Split(char[]? separator, StringSplitOptions options); public String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None); public String[] Split(params char[]? separator); public String[] Split(char[]? separator, int count); public String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None);
В качестве параметров метод Split
принимает один или несколько символов (Char
), используемых в качестве разделителя, а на выходе возвращает массив строк. Рассмотрим работу метода Split
на примере
string s14 = "Эта строка, которая будет разделена на подстроки с использованием двух разделителей"; string[] res = s14.Split(new char[] { ' ', ',' }); foreach (string s in res) { Console.WriteLine(s); }
Здесь в качестве разделителей мы используем два символа — пробел и запятую. Результатом выполнения кода будет следующий вывод в консоли:
Эта
строка
которая
будет
разделена
на
подстроки
с
использованием
двух
разделителей
Извлечение подстрок из строки в C#
Для извлечения подстрок из строки используется метод Substring
:
public String Substring(int startIndex); public String Substring(int startIndex, int length);
При использовании первого варианта метода (с одним параметром) из строки извлекается подстрока, начинающаяся с индекса startIndex
и, при этом, извлечение происходит до конца строки. Во втором случае подстрока извлекается также, начиная с индекса startIndex
, однако длина извлекаемой подстроки ограничивается вторым параметром — length
.
Пример использования метода представлен ниже:
string s15 = "hello world"; string s16 = s15.Substring(6); string s17 = s15.Substring(7, 3); Console.WriteLine(s16); Console.WriteLine(s17);
Результат выполнения
Изменение регистра строк в C#
Для изменения регистра символов в строке в C# можно воспользоваться двумя методами:
public String ToLower(); public String ToLower(CultureInfo? culture); public String ToUpper(); public String ToUpper(CultureInfo? culture);
Метод ToLower
меняет регистр всех символов в строке на нижний, а метод ToUpper
, напротив — меняет регистр всех символов в строке на верхний. Пример
string s15 = "HelLo World"; string s16 = s15.ToLower(); string s17 = s15.ToUpper(); Console.WriteLine(s16); Console.WriteLine(s17);
Результат выполнения
Обрезка строк в C#
Иногда требуется избавиться в строке от лишних символов в начале, в конце или одновременно и вначале и в конце. «Лишними» могут быть как обычные проблелы, так и прочие символы. Для обрезки строки в C# можно воспользоваться методами Trim*
:
public String Trim(); public String Trim(char trimChar); public String Trim(params char[]? trimChars); public String TrimEnd(char trimChar); public String TrimEnd(params char[]? trimChars); public String TrimStart(); public String TrimStart(char trimChar); public String TrimStart(params char[]? trimChars);
По названию метода можно понять смысл его работы. Так, если используется метод Trim()
, то обрезка строки происходит и сначала и с конца, если же используется TrimEnd()
, то строка обрезается только с конца. При этом, если используется версия метода без параметров, то из строки удаляются лидирующие или замыкающие пробелы, иначе — определенные в параметрах метода символы. Например,
string s15 = " HelLo World "; string s16 = s15.Trim(); //обрезаем пробелы string s17 = s16.Trim(new char[] {'H', 'd'}); //обрезаем заданные символы Console.WriteLine(s16); Console.WriteLine(s17);
Итого
В этой статье мы рассмотрели наиболее часто используемые методы работы со строками в C#. Конечно, работа со строками не ограничивается исключительно рассмотренными выше методами, однако, для начала работы нам этого будет достаточно. В дальнейшем мы рассмотрим также отдельно вопросы по форматированию строк, использование интерполяции строк и так далее.
уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.
В этой статье мы рассмотрим операции со строкой и подстрокой. Вы узнаете, как соединять и сравнивать строки, как извлекать символы и подстроки, как выполнять поиск в строке.
Соединение строк в Java
Чтобы соединить строки в Java, подойдёт операция сложения «+»:
String str1 = "Java"; String str2 = "Hi"; String str3 = str1 + " " + str2; System.out.println(str3); // Hi JavaЕсли же в предстоящей операции сложения строк будет применяться нестроковый объект, допустим, число, данный объект преобразуется к строке:
String str3 = "Год " + 2020;По факту, когда мы складываем строки с нестроковыми объектами, вызывается метод valueOf() класса String. Этот метод преобразует к строке почти все типы данных. Чтобы преобразовать объекты разных классов, valueOf вызывает метод toString() данных классов.
Объединять строки можно и с помощью concat():
String str1 = "Java"; String str2 = "Hi"; str2 = str2.concat(str1); // HiJavaМетод принимает строку, с которой нужно объединить вызывающую строку, возвращая нам уже соединённую строку.
Также мы можем использовать метод join(), позволяющий объединять строки с учетом разделителя. Допустим, две строки выше слились в слово «HiJava», однако мы бы хотели разделить подстроки пробелом. Тут и пригодится join():
String str1 = "Java"; String str2 = "Hi"; String str3 = String.join(" ", str2, str1); // Hi JavaМетод join — статический. Первый параметр — это разделитель, который будет использоваться для разделения подстрок в общей строке. Последующие параметры осуществляют передачу через запятую произвольного набора объединяемых подстрок — в нашем случае их две, но можно и больше.
Извлекаем символы и подстроки в Java
Чтобы извлечь символы по индексу, в классе String есть метод char charAt(int index). Этот метод принимает индекс, по которому необходимо получить символы, возвращая извлеченный символ:
String str = "Java"; char c = str.charAt(2); System.out.println(c); // vОбратите внимание, что индексация начинается с нуля, впрочем, как и в массивах.
Если же нужно извлечь сразу группу символов либо подстроку, подойдёт getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin). Этот метод принимает ряд параметров:
• srcBegin: индекс в нашей строке, с которого осуществляется начало извлечения символов;
• srcEnd: индекс в нашей строке, до которого осуществляется извлечение символов;
• dst: массив символов (именно в него будут эти символы извлекаться);
• dstBegin: индекс в массиве dst (с него надо добавлять символы, извлечённые из строки).String str = "Hi world!"; int start = 6; int end = 11; char[] dst=new char[end - start]; str.getChars(start, end, dst, 0); System.out.println(dst); // worldСравниваем строки в Java
Мы уже писали о том, как сравнивать строки в Java, используя для этого метод equals() (регистр учитывается) и equalsIgnoreCase() (регистр не учитывается). Хотелось бы сказать пару слов про ещё одну пару методов: int compareTo(String str) и int compareToIgnoreCase(String str) — они позволяют не только сравнить 2 строки, но и узнать, больше ли одна другой. Если значение, которое возвращается, больше 0, первая строка больше, если меньше нуля, всё наоборот. Когда обе строки равны, вернётся ноль.
Для определения используется лексикографический порядок. Допустим, строка «A» меньше строки «B», ведь символ ‘A’ в алфавите находится перед символом ‘B’. Когда первые символы строк равны, в расчёт берутся следующие символы. К примеру:
String str1 = "hello"; String str2 = "world"; String str3 = "hell"; System.out.println(str1.compareTo(str2)); // -15 - str1 меньше, чем strt2 System.out.println(str1.compareTo(str3)); // 1 - str1 больше, чем str3Поиск в строке в Java
Чтобы найти индекс первого вхождения подстроки в строку, используют метод indexOf(), последнего — метод lastIndexOf(). Если подстрока не найдена, оба метода вернут -1:
String str = "Hello world"; int index1 = str.indexOf('l'); // 2 int index2 = str.indexOf("wo"); //6 int index3 = str.lastIndexOf('l'); //9Чтобы определить, начинается строка с определённой подстроки, применяют метод startsWith(). Что касается метода endsWith(), то он даёт возможность определить оканчивается ли строка на определенную подстроку:
String str = "myfile.exe"; boolean start = str.startsWith("my"); //true boolean end = str.endsWith("exe"); //trueВыполняем замену в строке в Java
Заменить в нашей строке одну последовательность символов другой можно с помощью метода replace():
String str = "Hello world"; String replStr1 = str.replace('l', 'd'); // Heddo wordd String replStr2 = str.replace("Hello", "Bye"); // Bye worldОбрезаем строки в Java
Для удаления начальных и конечных пробелов применяют метод trim():
String str = " hello world "; str = str.trim(); // hello worldТакже существует метод substring() — он возвращает подстроку, делая это с какого-нибудь конкретного индекса до конца либо до определённого индекса:
String str = "Hello world"; String substr1 = str.substring(6); // world String substr2 = str.substring(3,5); //loМеняем регистр в Java
При необходимости вы можете перевести все символы вашей строки в нижний регистр (toLowerCase()) или в верхний (toUpperCase()):
String str = "Hello World"; System.out.println(str.toLowerCase()); // hello world System.out.println(str.toUpperCase()); // HELLO WORLDSplit
С помощью этого метода вы сможете разбить строку на подстроки по конкретному разделителю. Под разделителем понимается какой-либо символ либо набор символов, передаваемые в метод в качестве параметра. Давайте для примера разобьём небольшой текст на отдельные слова:
String text = "OTUS is a good company"; String[] words = text.split(" "); for(String word : words){ System.out.println(word); }В нашем случае строка разделится по пробелу, и мы получим следующий консольный вывод:
Вот и всё! Узнать больше всегда можно на наших курсах:
При написании статьи использовались материалы:
1. «Java-примеры: найти последнее вхождение подстроки в строке».
2. «Основные операции со строками».