strpos
strpos(string $haystack, string $needle, int $offset = 0): int|false
查找子串在字符串中首次出现的位置(索引)。
C C23
C23
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "hello world";
const char *pos = strstr(s, "world");
if (pos != NULL) {
printf("%ld\n", (long)(pos - s)); // 指针差即偏移量
} else {
printf("Not found\n"); // strstr 无匹配返回 NULL,对应 PHP 返回 false
}
// 字节偏移:UTF-8 下 "好" 从 "你好" 的第 3 字节开始
const char *zh = "你好";
const char *p2 = strstr(zh, "好");
printf("%ld\n", p2 ? (long)(p2 - zh) : -1L);
return 0;
}
输出
6 3
C++ C++26
C++26
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
std::cout << s.find("world") << "\n"; // npos 表示未找到
std::cout << std::string("你好").find("好") << "\n"; // 字节偏移:UTF-8 下为 3
return 0;
}
输出
6 3
C# v11.0.100
v11.0.100
Console.WriteLine("hello world".IndexOf("world"));
// IndexOf 按 UTF-16 代码单元计数:"好" 在下标 1(字符而非字节)
Console.WriteLine("你好".IndexOf("好"));
输出
6 1
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("hello world", "world"))
// Index 返回字节偏移:"好" 在 "你好" 中为 3
fmt.Println(strings.Index("你好", "好"))
}
输出
6 3
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println("hello world".indexOf("world"));
// indexOf 按 UTF-16 代码单元计数:"好" 在下标 1(字符而非字节)
System.out.println("你好".indexOf("好"));
}
}
输出
6 1
JavaScript v26.13.1
v26.13.1
console.log("hello world".indexOf("world"))
// indexOf 按 UTF-16 代码单元计数:"好" 在下标 1(字符而非字节)
console.log("你好".indexOf("好"))
输出
6 1
PHP v8.6.0
v8.6.0
echo strpos("hello world", "world"), "\n";
// 经典坑:位置 0 的匹配是假值——必须用 !== false 比较
var_dump(strpos("hello", "h") === 0, strpos("hello", "world") === false);
// 查找按字节计数:"好" 从 "你好" 的第 3 字节开始
echo strpos("你好", "好");
输出
6 bool(true) bool(true) 3
Python v3.15.2
v3.15.2
print("hello world".find("world"))
print("你好".find("好")) # str 下标按字符计数:1(不是字节)
输出
6 1
Rust v1.99.1
v1.99.1
fn main() {
let s = "hello world";
match s.find("world") {
Some(i) => println!("{}", i), // 命中:字节偏移
None => println!("Not found"), // 无匹配(此时 PHP 返回 false)
}
println!("{:?}", s.find("xyz")); // 无匹配示例:None
let zh = "你好";
// find() 返回字节偏移:"好" 为 3(每个中日韩字符占 3 个 UTF-8 字节)
println!("{}", zh.find("好").unwrap());
}
输出
6 None 3
TypeScript v26.13.1
v26.13.1
const s: string = "hello world";
console.log(s.indexOf("world"));
console.log("你好".indexOf("好")); // UTF-16 代码单元:1(字符而非字节)
输出
6 1
语言差异说明
C:以 strstr() 定位子串,未命中返回 NULL,示例已做判断(PHP 此时返回 false)。
Go:strings.Index 返回 -1;返回值以字节计。
Java:indexOf 返回 -1;以 UTF-16 代码单元计。
JavaScript:indexOf 返回 -1;以 UTF-16 代码单元计。
PHP:找不到时返回 false(不是 -1),且位置 0 的匹配是假值、必须用 !== false 比较;返回值单位以字节计——本条目已用 UTF-8 中文 "你好" 实证 "好" 在字节下标 3。
Python:find 返回 -1;以 Unicode 代码点计。
Rust:find 返回 Option<usize>(未命中为 None),示例演示了命中与未命中两种分支。