C's string.strchr in TypeScript

Rosetta Stone: php/strchr

How to use

Install via yarn add locutus and import: import { strchr } from 'locutus/c/string/strchr'.

Or with CommonJS: const { strchr } = require('locutus/c/string/strchr')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1strchr('Hello, World!', 'o')'o, World!'
2strchr('Hello', 'x')null

C types and TypeScript/JavaScript

C is statically typed while TypeScript/JavaScript is dynamically typed. Locutus C functions accept TypeScript/JavaScript's flexible types but are only parity-verified for inputs that would be valid in C.

For example, abs() in TypeScript/JavaScript accepts floats (like C's fabs()) and handles strings gracefully, but only integer inputs are verified against native C. This pragmatic approach gives you the expected C behavior for valid inputs while leveraging TypeScript/JavaScript's flexibility for edge cases.

Notes

  • Returns a pointer to the first occurrence of c in str. In JS, returns the substring starting from the first occurrence, or null.

Here's what our current TypeScript equivalent to C's strchr found in the string.h header file looks like.

export function strchr(str: string, c: string): string | null {
// discuss at: https://locutus.io/c/string/strchr/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns a pointer to the first occurrence of c in str.
// note 1: In JS, returns the substring starting from the first occurrence, or null.
// example 1: strchr('Hello, World!', 'o')
// returns 1: 'o, World!'
// example 2: strchr('Hello', 'x')
// returns 2: null

str = str + ''
c = (c + '').charAt(0)
const idx = str.indexOf(c)
return idx === -1 ? null : str.slice(idx)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 20 C functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More C string functions


Star