Skip to content

Instantly share code, notes, and snippets.

@cmkilger
Created August 24, 2018 17:39
Show Gist options
  • Save cmkilger/bd83672e4854680e9506955536989901 to your computer and use it in GitHub Desktop.
Save cmkilger/bd83672e4854680e9506955536989901 to your computer and use it in GitHub Desktop.
Code samples to get a substring using a UTF-16 range

Substrings from UTF-16 ranges

All these code examples produce the following output.

5
😀

Swift

import Foundation

let test = "Hi😀!" as NSString
let location = 2
let length = 2
print(test.length)
print(test.substring(with: NSRange(location: location, length: length)))

Objective-C

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSString *test = @"Hi😀!";
        NSInteger location = 2;
        NSInteger length = 2;
        printf("%lu\n", [test length]);
        printf("%s\n", [[test substringWithRange:NSMakeRange(location, length)] cStringUsingEncoding:NSUTF8StringEncoding]);
    }
}

Java

class Parse {
    public static void main(String[] args) {
        String test = "Hi😀!";
        int location = 2;
        int length = 2;
        System.out.println(test.length());
        System.out.println(test.substring(location, location+length));
    }
}

Kotlin

fun main(args: Array<String>) {
    val test = "Hi😀!"
    val location = 2;
    val length = 2;
    println(test.length)
    println(test.substring(location, location+length))
}

Javascript

let test = "Hi😀!"
let location = 2
let length = 2
console.log(test.length)
console.log(test.substr(location, length))

PHP

<?php

$test = "Hi😀!";
$location = 2;
$length = 2;
echo (strlen(mb_convert_encoding($test, 'UTF-16', 'UTF-8'))/2)."\n";
echo mb_convert_encoding(substr(mb_convert_encoding($test, 'UTF-16', 'UTF-8'), $location*2, $length*2), 'UTF-8', 'UTF-16')."\n";

Erlang

fun main(args: Array<String>) {
    val test = "Hi😀!"
    val location = 2;
    val length = 2;
    println(test.length)
    println(test.substring(location, location+length))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment