如何找到給定字符串中兩個子字符串值之間的距離?例如,如果我有這個詞很棒,我想找到「我」之間的距離(相距一個空格)。謝謝你的幫助。2個子字符串之間的距離
0
A
回答
0
有很多選擇,你可以處理,但這是從哪裏開始。
1
$haystack = 'terrific';
$needle = 'i';
$distance = false;
$pos1 = strpos($haystack,$needle);
if ($pos1 !== false) {
$pos2 = strpos($haystack,$needle,$pos1+1);
if ($pos2 !== false) {
$distance = $pos2 - $pos1;
}
}
編輯
或
$haystack = 'terrific';
$needle = 'i';
$distance = false;
$needlePositions = array_keys(array_intersect(str_split($haystack),array($needle)));
if (count($needlePositions) > 1) {
$distance = $needlePositions[1] - $needlePositions[0];
}
+0
+1 OP可能會將'$ pos1 + 1'更改爲'$ pos1 + strlen($ needle)'以使用長度超過一個字符的針。還應該將'$ distance'遞減爲'6-4 = 2',並且OP需要'1',即中間的一個字符。 – webbiedave 2011-05-13 23:12:49
1
這裏有一些方法與評價在線:
// We take our string
$mystring = "terrific";
// Then the first character we want to look for
$mychar1 = "i";
$mychar2 = "i";
// Now we get the position of the first character
$position1 = strpos($mystring, $mychar1);
// Now we use the last optional parameter offset to get the next i
// We have to go one beyond the previous position for this to work
// Properly
$position2 = strpos($mystring, $mychar2, ($position1 + 1));
// Then we get the distance
echo "Distance is: " . ($position2 - $position1) . "\n";
// We can also use strrpos to find the distance between the first and last i
// if there are more than one
$mystring2 = "terrific sunshine";
$position2 = strrpos($mystring2, $mychar2);
echo "Distance is: " . ($position2 - $position1) . "\n";
相關問題
- 1. VBA - 2個字符串之間的距離
- 2. 2個MKAnnotations之間的距離?
- 3. 2個latlon點之間的距離
- 4. 計算兩個字符串之間的levenshtein距離
- 5. 使用for循環來獲得2個字符串之間的漢明距離
- 6. 2字符串之間的字符串
- 7. 距離之間的兩個
- 8. 計算Levenshtein許多連續字符串之間的距離
- 9. 字符串之間的最小距離函數
- 10. 計算2 lat long之間的距離
- 11. 編輯距離爲2的字符串的散列技術2
- 12. 編輯字符串距編輯距離最短的字符串
- 13. C#:如何刪除2個字符串之間的匹配子字符串?
- 14. 在python中提取2個字符串之間的字符串?
- 15. 查找2個字符串之間的字符串值
- 16. 在Java中的2個字符串之間替換字符串
- 17. 替換2個特定字符之間的字符串字符
- 18. 查找2個字符串之間的最大子序列
- 19. 可可得到2個字符之間的多個子字符串
- 20. 找出字符串中兩個特定單詞之間的距離
- 21. 如何找到兩個字符串之間的子字符串?
- 22. 提取Haskell中兩個子字符串之間的字符串
- 23. 查找兩個字符串之間的所有子字符串
- 24. 2個或多個放置針腳之間的距離
- 25. Levenstein距離子串
- 26. 基於2個物體之間的距離的Lerp顏色
- 27. 計算在(Python)的2個.vtk文件之間的距離
- 28. A,B之間的距離
- 29. 車牌之間的距離
- 30. 捕獲python中2個字符之間的特殊字符串
有你嘗試過什麼? – 2011-05-13 22:59:58
如果在字符串中有三個i,你想要兩個鄰居中最小的,最大的,最左邊到最右邊的節點? – 2011-05-13 23:01:45