is_string

is_string(mixed $value): bool

检测变量是否为字符串类型。

C C23

C23
#include <stdio.h>

#define is_string(x) _Generic((x), char*: 1, const char*: 1, default: 0)

int main(void) {
    const char *s = "abc";
    int n = 42;
    printf("%d %d\n", is_string(s), is_string(n));
    return 0;
}
输出
1 0

C++ C++26

C++26
#include <iostream>
#include <string>
#include <type_traits>
int main() {
    std::string s = "abc";
    int n = 42;
    std::cout << std::boolalpha
              << std::is_same_v<decltype(s), std::string> << " "
              << std::is_same_v<decltype(n), std::string> << "\n";
    return 0;
}
输出
true false

C# v11.0.100

v11.0.100
object[] xs = { "abc", 42 };
Console.WriteLine(xs[0] is string);
Console.WriteLine(xs[1] is string);
输出
True
False

Go v1.27.4

v1.27.4
package main

import "fmt"

func isString(v any) bool {
    _, ok := v.(string)
    return ok
}

func main() {
    fmt.Println(isString("abc"), isString(42))
}
输出
true false

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        Object[] xs = { "abc", 42 };
        System.out.println(xs[0] instanceof String);
        System.out.println(xs[1] instanceof String);
    }
}
输出
true
false

JavaScript v26.13.1

v26.13.1
console.log([typeof "abc" === "string", typeof 42 === "string"]);
输出
[ true, false ]

PHP v8.6.0

v8.6.0
echo json_encode([is_string("abc"), is_string(42)]);
输出
[true,false]

Python v3.15.2

v3.15.2
print([isinstance(x, str) for x in ["abc", 42]])
输出
[True, False]

Rust v1.99.1

v1.99.1
use std::any::Any;

fn main() {
    let xs: Vec<Box<dyn Any>> = vec![Box::new("abc".to_string()), Box::new(42i32)];
    for x in &xs {
        println!("{}", x.is::<String>());
    }
}
输出
true
false

TypeScript v26.13.1

v26.13.1
const xs: (string | number)[] = ["abc", 42];
console.log(xs.map((x) => typeof x === "string"));
输出
[ true, false ]

语言差异说明

C:用 _Generic 在编译期按类型分派。

C++:用 std::is_same_v 在编译期按类型分派。

C#:在 object 容器上用 is。

Go:用类型断言 v.(string)。

Java:静态类型语言变量类型编译期已知,在 object 容器上用 instanceof。

JavaScript:用 typeof x === "string"。

PHP:is_string 严格判断字符串标量类型。

Python:用 isinstance(x, str)。

Rust:装箱为 Box<dyn Any> 后用 Any::is 下行转换检查。

TypeScript:同 JS,typeof x === "string"。