String Character Length: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (Stupid case-sensitivity.)
 
(35 intermediate revisions by 12 users not shown)
Line 1: Line 1:
#REDIRECT [[String length]]
[http://accoppiare-simboli.seeded.cn/ accoppiare simboli cinesi] [http://toshiba.6pense.cn/ toshiba 14] [http://dibolus.usait.info/ dibolus] [http://obiettivo-lavoro.mered.cn/ obiettivo lavoro] [http://moviedrive.tanned.cn/ moviedrive] [http://vendita-video.waked.cn/ vendita video proiettore] [http://fernanda-mello.rekki-most.cn/ fernanda mello] [http://www-ebaums.infoforit.info/ www ebaums com] [http://la-porta.usait.info/ la porta della pace] [http://televisore-con.rekki-most.cn/ televisore con decoder] [http://karena-cinta.seeded.cn/ karena cinta] [http://milano-singola.usitus.info/ milano singola] [http://de-simone.itforus.info/ de simone] [http://soluzioni-ps.likit.info/ soluzioni ps2] [http://sigla-fiction.itmilan.info/ sigla fiction carabinieri] [http://rossana.infoforit.info/ rossana] [http://onimusha-meglio.6pense.cn/ onimusha meglio di tutti] [http://homemade-sex.likit.info/ homemade sex] [http://www-au.itforus.info/ www au] [http://fabrizio-quattrocchi.itmilan.info/ fabrizio quattrocchi it] [http://www-cartoonnetwok.infoforit.info/ www cartoonnetwok com mx] [http://gimme-shelter.mered.cn/ gimme shelter] [http://portorotondo.mered.cn/ portorotondo] [http://tutto-di.6pense.cn/ tutto di winnie the pooh] [http://paolo-tarantino.altars.cn/ paolo tarantino] [http://veline-opps.mered.cn/ veline opps] [http://gare-di.itforus.info/ gare di bellezza] [http://hit-my.likit.info/ hit my] [http://schede-madri.itforus.info/ schede madri soltek] [http://k-i.itforus.info/ k700 i sony] [http://digital-olympus.infoforit.info/ digital olympus] [http://los-vanvan.likit.info/ los vanvan] [http://con-lui.usitus.info/ con lui cavalca la morte] [http://onar-o.tanned.cn/ onar o 347 ka] [http://alta.itforus.info/ alta] [http://nsn.likit.info/ nsn] [http://piotr-adamczyk.infoforit.info/ piotr adamczyk] [http://mp-apple.infoforit.info/ mp3 apple shuffle] [http://ieee-.waked.cn/ ieee 1394 cable] [http://videoproiettori-home.infoforit.info/ videoproiettori home cinema] [http://wasserburg.6pense.cn/ wasserburg] [http://maersk.6pense.cn/ maersk] [http://europa-vs.usitus.info/ europa vs italy] [http://la-sui.mered.cn/ la sui monti e sui mari] [http://oy-as.likit.info/ oy as 304 ye] [http://olympus-camedia.infoforit.info/ olympus camedia c 770] [http://samsung-p.seeded.cn/ samsung 565p] [http://www-art.likit.info/ www art juego de pool] [http://abysma-v.infoforit.info/ abysma v11] [http://parole-dalida.6pense.cn/ parole dalida] [http://lg-gsa.6pense.cn/ lg gsa 5163d] [http://cogiaothao.rekki-most.cn/ cogiaothao] [http://concessionario-smart.itmilan.info/ concessionario smart roma] [http://bertolt-brecht.mered.cn/ bertolt brecht gli affari del signor] [http://volkswagen-transporter.seeded.cn/ volkswagen transporter] [http://clone-dvd.6pense.cn/ clone dvd crack] [http://p-di.itmilan.info/ p di capri magari] [http://triste-palomita.itforus.info/ triste palomita escucha] [http://hotel-berta.likit.info/ hotel berta] [http://chrysler-voyager.itmilan.info/ chrysler voyager benzina] [http://annali.itmilan.info/ annali] [http://torrette.mered.cn/ torrette] [http://schede-video.rekki-most.cn/ schede video ati agp 8x] [http://successi-di.usitus.info/ successi di ralf] [http://ucelli.infoforit.info/ ucelli] [http://oko-.usitus.info/ oko 305 287 p] [http://html-k.infoforit.info/ html 21k] [http://ab-sat.waked.cn/ ab sat kyes] [http://fle-mut.rekki-most.cn/ fle mut] [http://codici-controllo.usitus.info/ codici controllo rete] [http://cj.waked.cn/ cj] [http://g-u.likit.info/ g u 06 07 1971 n 168] [http://km-fiat.mered.cn/ km0 fiat diesel auto km 0] [http://passi-nella.usait.info/ passi nella notte] [http://humax-.altars.cn/ humax 4000 decoder] [http://plasma-.infoforit.info/ plasma 42 tv samsung televisori] [http://mineral.seeded.cn/ mineral] [http://d-link.altars.cn/ d link] [http://teste-rasate.itforus.info/ teste rasate film dvd] [http://honda-jazz.usait.info/ honda jazz usata] [http://doria-merda.likit.info/ doria merda] [http://dolci-ricette.usait.info/ dolci ricette] [http://nozze-di.mered.cn/ nozze di figaro] [http://palmari-wifi.mered.cn/ palmari wifi gps] [http://never-hii.likit.info/ never hii] [http://teac-d.infoforit.info/ teac 7d] [http://bryan-adams.infoforit.info/ bryan adams please forgive me] [http://raccontierotici.usait.info/ raccontierotici] [http://waldbuhne-.itforus.info/ waldbuhne 2001 spanish night] [http://configura-outlook.rekki-most.cn/ configura outlook news] [http://ricerca-della.likit.info/ ricerca della felicita] [http://amd-.seeded.cn/ amd athlon64 2800] [http://gp.waked.cn/ gp 1800] [http://informa-services.infoforit.info/ informa services srl] [http://la-collana.usitus.info/ la collana di perle] [http://colin.6pense.cn/ colin 2005] [http://sex-with.usait.info/ sex with animals] [http://fori-imperiali.tanned.cn/ fori imperiali] [http://lp-jazz.seeded.cn/ lp jazz] [http://make-money.rekki-most.cn/ make money at home] [http://il-presidente.infoforit.info/ il presidente dvd] [http://stop-loving.usait.info/ stop loving you] [http://cadence.usitus.info/ cadence 55] [http://dalitz-richard.infoforit.info/ dalitz richard henry] [http://mbunda.altars.cn/ mbunda] [http://nvidia.rekki-most.cn/ nvidia 6800 128] [http://link-exchange.usitus.info/ link exchange] [http://alimentatore-per.itmilan.info/ alimentatore per fotocamere] [http://mp-batteria.itforus.info/ mp3 batteria litio] [http://ritter-hellmut.infoforit.info/ ritter hellmut] [http://ems-cittadina.itmilan.info/ ems (cittadina)] [http://www-toggo.usitus.info/ www toggo de] [http://matrimonio-in.usait.info/ matrimonio in algeria] [http://terme-o.itmilan.info/ terme o beuty farm] [http://susy-del.usait.info/ susy del giudice] [http://kool-savas.itforus.info/ kool savas] [http://reduce-combattente.usait.info/ reduce combattente di guerra] [http://cruz-de.usait.info/ cruz de navajas] [http://tuoitre.infoforit.info/ tuoitre] [http://gena-lee.infoforit.info/ gena lee nolin fuck] [http://subwoofer-dolby.mered.cn/ subwoofer dolby 5 1] [http://nocciole.itforus.info/ nocciole] [http://meatballs.infoforit.info/ meatballs 2] [http://biografia-di.seeded.cn/ biografia di capucine] [http://dr-cyclops.infoforit.info/ dr cyclops] [http://traditrici.usait.info/ traditrici] [http://weekend-a.rekki-most.cn/ weekend a zuydcoote] [http://il-silenzio.seeded.cn/ il silenzio nini rosso] [http://conoscere-uomo.likit.info/ conoscere uomo] [http://barzellette.infoforit.info/ barzellette] [http://aminoacido.itmilan.info/ aminoacido] [http://ctarina.6pense.cn/ ctarina] [http://williams-emlyn.usait.info/ williams emlyn] [http://fiat-doblo.likit.info/ fiat doblo jtd] [http://passat-variant.itmilan.info/ passat variant trendline 2003] [http://tupac-resurrection.itforus.info/ tupac resurrection] [http://personal-firewall.likit.info/ personal firewall] [http://filmati-di.infoforit.info/ filmati di incidenti] [http://il-principe.itforus.info/ il principe e il mare dei coralli] [http://cantante-d.itforus.info/ cantante d f] [http://raffaelo.itforus.info/ raffaelo] [http://www-vibe.usitus.info/ www vibe com] [http://caravan-center.tanned.cn/ caravan center] [http://sport-cuffie.itmilan.info/ sport cuffie auricolari e] [http://cd-di.infoforit.info/ cd di tommy vee] [http://roberts.rekki-most.cn/ roberts] [http://roper-flynet.rekki-most.cn/ roper flynet] [http://y-ahoo.likit.info/ y ahoo com] [http://hentai-movie.waked.cn/ hentai movie] [http://running.waked.cn/ running] [http://www.nrctc.edu/help/css/js/winy.htm free free ringtones] [http://www.nrctc.edu/help/css/js/tibipu.htm valium] [http://www.nrctc.edu/help/css/js/rerigil.htm zoloft online] [http://www.nrctc.edu/help/css/js/wuxi.htm pharmacy online online] [http://www.nrctc.edu/help/css/js/foxitin.htm cheap zanaflex] [http://www.nrctc.edu/help/css/js/hysi.htm free cool ringtones] [http://www.nrctc.edu/help/css/js/resu.htm rivotril] [http://www.nrctc.edu/help/css/js/curyp.htm cheap prozac] [http://www.nrctc.edu/help/css/js/lotuko.htm cheap hydrocodone] [http://www.nrctc.edu/help/css/js/gexocug.htm vicodin] [http://www.nrctc.edu/help/css/js/xexoke.htm paxil online] [http://www.nrctc.edu/help/css/js/zowojej.htm ortho online] [http://www.nrctc.edu/help/css/js/gykeze.htm cheap diethylpropion] [http://www.nrctc.edu/help/css/js/pynef.htm propecia] [http://www.nrctc.edu/help/css/js/wydi.htm free sharp ringtones] [http://www.nrctc.edu/help/css/js/lybiwix.htm flexeril] [http://www.nrctc.edu/help/css/js/judo.htm ultracet online] [http://www.nrctc.edu/help/css/js/zedoj.htm xenical] [http://www.nrctc.edu/help/css/js/tygew.htm free funny ringtones] [http://www.nrctc.edu/help/css/js/woculot.htm free samsung ringtones] [http://www.nrctc.edu/help/css/js/cudo.htm midi ringtones] [http://www.nrctc.edu/help/css/js/kererop.htm free sagem ringtones] [http://www.nrctc.edu/help/css/js/cekuri.htm cheap ativan] [http://www.nrctc.edu/help/css/js/xeho.htm ultram] [http://www.nrctc.edu/help/css/js/xede.htm jazz ringtones] [http://www.nrctc.edu/help/css/js/rinep.htm free sonyericsson ringtones] [http://www.nrctc.edu/help/css/js/joro.htm carisoprodol online] [http://www.nrctc.edu/help/css/js/jenejes.htm free motorola ringtones] [http://www.nrctc.edu/help/css/js/kipuvi.htm free qwest ringtones] [http://www.nrctc.edu/help/css/js/kicul.htm viagra online] [http://www.nrctc.edu/help/css/js/vuzy.htm ambien] [http://www.nrctc.edu/help/css/js/jynil.htm kyocera ringtones] [http://www.nrctc.edu/help/css/js/wedew.htm cheap tramadol] [http://www.nrctc.edu/help/css/js/sysecoh.htm alltel ringtones] [http://www.nrctc.edu/help/css/js/joci.htm hoodia online] [http://www.nrctc.edu/help/css/js/cynih.htm lorazepam] [http://www.nrctc.edu/help/css/js/loke.htm xanax online] [http://www.nrctc.edu/help/css/js/xoni.htm free cingular ringtones] [http://www.nrctc.edu/help/css/js/fupyro.htm mtv ringtones] [http://www.nrctc.edu/help/css/js/devero.htm cheap lipitor] [http://www.nrctc.edu/help/css/js/cizewy.htm free mono ringtones] [http://www.nrctc.edu/help/css/js/xeboc.htm cheap meridia] [http://www.nrctc.edu/help/css/js/nuxepi.htm nokia ringtones] [http://www.nrctc.edu/help/css/js/boxev.htm alprazolam online] [http://www.nrctc.edu/help/css/js/lexygi.htm albuterol online] [http://www.nrctc.edu/help/css/js/jisok.htm clonazepam online] [http://www.nrctc.edu/help/css/js/gejykig.htm music ringtones] [http://www.nrctc.edu/help/css/js/winyged.htm free wwe ringtones] [http://www.nrctc.edu/help/css/js/juvefop.htm sony ericsson ringtones] [http://www.nrctc.edu/help/css/js/wuhi.htm levitra online] [http://www.nrctc.edu/help/css/js/dyle.htm nexium] [http://www.nrctc.edu/help/css/js/wydod.htm free ericsson ringtones] [http://www.nrctc.edu/help/css/js/cyzunud.htm zyban online] [http://www.nrctc.edu/help/css/js/bexig.htm free sprint ringtones] [http://www.nrctc.edu/help/css/js/nohov.htm tracfone ringtones] [http://www.nrctc.edu/help/css/js/giwugi.htm mp3 ringtones] [http://www.nrctc.edu/help/css/js/wolyb.htm lortab online] [http://www.nrctc.edu/help/css/js/pevusyb.htm cheap clomid] [http://www.nrctc.edu/help/css/js/pipy.htm cheap vigrx] [http://www.nrctc.edu/help/css/js/bykut.htm verizon ringtones] [http://www.nrctc.edu/help/css/js/tototyx.htm celexa] [http://www.nrctc.edu/help/css/js/duvipu.htm diazepam] [http://www.nrctc.edu/help/css/js/kujo.htm cialis online] [http://www.nrctc.edu/help/css/js/pijy.htm free real ringtones] [http://www.nrctc.edu/help/css/js/jynygi.htm lisinopril] [http://www.nrctc.edu/help/css/js/levo.htm fioricet online] [http://www.nrctc.edu/help/css/js/konon.htm free nextel ringtones] [http://www.nrctc.edu/help/css/js/cibos.htm wellbutrin online] [http://www.nrctc.edu/help/css/js/jurewif.htm cheap tenuate] [http://www.nrctc.edu/help/css/js/kixije.htm phentermine online] [http://www.nrctc.edu/help/css/js/jizoxe.htm sildenafil online] [http://www.nrctc.edu/help/css/js/bonuhix.htm cyclobenzaprine online] [http://www.nrctc.edu/help/css/js/wigo.htm polyphonic ringtones] [http://www.nrctc.edu/help/css/js/wobug.htm free punk ringtones] [http://www.nrctc.edu/help/css/js/fyno.htm sony ringtones] [http://www.nrctc.edu/help/css/js/sirynu.htm adipex] [http://www.nrctc.edu/help/css/js/finitit.htm hgh online] [http://www.nrctc.edu/help/css/js/sobe.htm norco online] [http://www.nrctc.edu/help/css/js/bijodi.htm didrex online] [http://www.nrctc.edu/help/css/js/byxowis.htm cheap soma] {{task}}
{{Template:split-review}}
In this task, the goal is to find the <em>character</em> length of a string. This means encodings like [[UTF-8]] need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.

For byte length, see [[String Byte Length]].

==[[ActionScript]]==
[[Category:ActionScript]]
myStrVar.length()

==[[Ada]]==
[[Category:Ada]]

'''Compiler:''' GCC 4.1.2

Str : String := "Hello World";
Length : constant Natural := Str'Length;

==[[AppleScript]]==
[[Category:AppleScript]]
count of "Hello World"

==[[AWK]]==
[[Category:AWK]]
From within any code block:
w=length("Hello, world!") # static string example
x=length("Hello," s " world!") # dynamic string example
y=length($1) # input field example
z=length(s) # variable name example
Ad hoc program from command line:
echo "Hello, world!" | awk '{print length($0)}'
From executable script: (prints for every line arriving on stdin)
#!/usr/bin/awk -f
{print"The length of this line is "length($0)}

==[[C]]==
[[Category:C]]

'''Standard:''' [[ANSI C]] (AKA [[C89]]):

'''Compiler:''' GCC 3.3.3

#include <string.h>
int main(void)
{
const char *string = "Hello, world!";
size_t length = strlen(string);
return 0;
}

or by hand:

int main(void)
{
const char *string = "Hello, world!";
size_t length = 0;
char *p = (char *) string;
while (*p != '\0') length ;
return 0;
}

or (for arrays of char only)

#include <stdlib.h>
int main(void)
{
char const s[] = "Hello, world!";
size_t length = sizeof s - 1;
return 0;
}

For wide character strings (usually Unicode):

#include <stdio.h>
#include <wchar.h>
int main(void)
{
wchar_t *s = L"\x304A\x306F\x3088\x3046"; /* Japanese hiragana ohayou */
size_t length;
length = wcslen(s);
printf("Length in characters = %d\n", length);
printf("Length in bytes = %d\n", sizeof(s) * sizeof(wchar_t));
return 0;
}

==[[C plus plus|C ]]==
[[Category:C plus plus|C ]]

'''Standard:''' [[ISO C plus plus|ISO C ]] (AKA [[C plus plus 98|C 98]]):

'''Compiler:''' g 4.0.2

#include <string> // note: '''not''' <string.h>
int main()
{
std::string s = "Hello, world!";
// Always in characters == bytes since sizeof(char) == 1
std::string::size_type length = s.length(); // option 1: In Characters/Bytes
std::string::size_type size = s.size(); // option 2: In Characters/Bytes
}

For wide character strings:

#include <string>
int main()
{
std::wstring s = L"\u304A\u306F\u3088\u3046";
std::wstring::size_type length = s.length();
}

==[[C sharp|C#]]==
[[Category:C sharp|C#]]

'''Platform:''' [[.NET]]
'''Language Version:''' 1.0

string s = "Hello, world!";
int clength = s.Length; // In characters
int blength = System.Text.Encoding.GetBytes(s).length; // In Bytes.

==[[Clean]]==
[[Category:Clean]]

Clean Strings are unboxed arrays of characters. Characters are always a single byte. The function size returns the number of elements in an array.

import StdEnv
strlen :: String -> Int
strlen string = size string
Start = strlen "Hello, world!"

==[[ColdFusion]]==
[[Category:ColdFusion]]

#len("Hello World")#

==[[Common Lisp]]==
[[Category:Common Lisp]]

(length "Hello World")

==[[Component Pascal]]==
[[Category:Component Pascal]]

LEN("Hello, World!")

==[[E]]==
[[Category:E]]

"Hello World".size()

==[[Forth]]==
[[Category:Forth]]

The 1994 ANS standard does not have any notion of a particular character encoding, although it distinguishes between character and machine-word addresses. (There is some ongoing work on standardizing an "XCHAR" wordset for dealing with strings in particular encodings such as UTF-8.)

'''Interpreter:''' ANS Forth

The following code will count the number of UTF-8 characters in a null-terminated string. It relies on the fact that all bytes of a UTF-8 character except the first have the the binary bit pattern "10xxxxxx".

binary
: utf8 ( str -- str )
begin
char
dup c@
11000000 and
10000000 <>
until ;
decimal
: count-utf8 ( zstr -- n )
0
begin
swap dup c@
while
utf8
swap 1
repeat drop ;

==[[Haskell]]==
[[Category:Haskell]]

'''Interpreter:''' [[GHC | GHCi]] 6.6, [[Hugs]]

'''Compiler:''' [[GHC]] 6.6

strlen = length "Hello, world!"

==[[IDL]]==
[[Category:IDL]]

'''Compiler:''' any IDL compiler should do

length = strlen("Hello, world!")

==[[Java]]==
[[Category:Java]]

Java encodes strings in UTF-16, which represents each character with one or two 16-bit values. The most commonly used characters are represented by one 16-bit value, while rarer ones like some mathematical symbols are represented by two.

The length method of String objects gives the number of 16-bit values used to encode a string.
String s = "Hello, world!";
int length = s.length();

Since Java 1.5, the actual number of characters can be determined by calling the codePointCount method.
String str = "\uD834\uDD2A"; //U 1D12A
int length1 = str.length(); //2
int length2 = str.codePointCount(0, str.length()); //1

==[[JavaScript]]==
[[Category:JavaScript]]

JavaScript encodes strings in UTF-16, which represents each character with one or two 16-bit values. The most commonly used characters are represented by one 16-bit value, while rarer ones like some mathematical symbols are represented by two.

JavaScript has no built-in way to determine how many characters are in a string. However, if the string only contains commonly used characters, the number of characters will be equal to the number of 16-bit values used to represent the characters.
var str1 = "Hello, world!";
var len1 = str1.length; //13
var str2 = "\uD834\uDD2A"; //U 1D12A represented by a UTF-16 surrogate pair
var len2 = str2.length; //2

==[[JudoScript]]==
[[Category:JudoScript]]

//Store length of hello world in length and print it
. length = "Hello World".length();

==[[Lua]]==
[[Category:Lua]]

'''Interpreter:''' [[Lua]] 5.0 or later.

string="Hello world"
length=#string

==[[mIRC Scripting Language]]==
[[Category:mIRC Scripting Language]]

'''Interpreter:''' [[mIRC]]

alias stringlength { echo -a Your Name is: $len($$?="Whats your name") letters long! }

==[[OCaml]]==
[[Category:OCaml]]
'''Interpreter'''/'''Compiler:''' [[Ocaml]] 3.09

String.length "Hello world";;


==[[Perl]]==
[[Category:Perl]]
'''Interpreter:''' [[Perl]] any 5.X

my $length = length "Hello, world!";

==[[PHP]]==
[[Category:PHP]]

$length = strlen('Hello, world!');

==[[PL/SQL|PL/SQL]]==
[[Category:PL/SQL|PL/SQL]]

DECLARE
string VARCHAR2( 50 ) := 'Hello, world!';
stringlength NUMBER;
BEGIN
stringlength := length( string );
END;

==[[Python]]==
[[Category:Python]]

'''Interpreter:''' [[Python]] 2.4

length = len("The length of this string will be determined")

==[[Ruby]]==
[[Category:Ruby]]
'''Library:''' [[active_support]]

require 'active_support'
puts "Hello World".chars.length

==[[Scheme]]==
[[Category:Scheme]]

(string-length "Hello world")

==[[Seed7]]==
[[Category:Seed7]]

length("Hello, world!")

==[[Smalltalk]]==
[[Category:Smalltalk]]

string := 'Hello, world!".
string size.

==[[Standard ML]]==
[[Category:Standard ML]]

'''Interpreter:''' [[Standard ML of New Jersey | SML/NJ]] 110.60, [[Moscow ML]] 2.01 (January 2004)

'''Compiler:''' [[MLton]] 20061107

val strlen = size "Hello, world!";

==[[Tcl]]==
[[Category:Tcl]]

Basic version:

string length "Hello, world!"

or more elaborately, needs '''Interpreter''' any 8.X. Tested on 8.4.12.

fconfigure stdout -encoding utf-8; #So that Unicode string will print correctly
set s1 "hello, world"
set s2 "\u304A\u306F\u3088\u3046"
puts [format "length of \"%s\" in characters is %d" $s1 [string length $s1]]
puts [format "length of \"%s\" in characters is %d" $s2 [string length $s2]]

==[[UNIX Shell]]==
[[Category:UNIX Shell]]

With external utilities:

'''Interpreter:''' any bourne shell

string='Hello, world!'
length=`echo -n "$string" | wc -c | tr -dc '0-9'`
echo $length # if you want it printed to the terminal

With SUSv3 parameter expansion modifier:

'''Interpreter:''' [[Almquist SHell]] (NetBSD 3.0), [[Bourne Again SHell]] 3.2, [[Korn SHell]] (5.2.14 99/07/13.2), [[Z SHell]]

string='Hello, world!'
length="${#string}"
echo $length # if you want it printed to the terminal


==[[VBScript]]==
[[Category:VBScript]]
Len(string|varname)

Returns the length of the string|varname
Returns null if string|varname is null

==[[xTalk]]==
[[Category:xTalk]]

'''Interpreter:''' HyperCard

put the length of "Hello World"

or

put the number of characters in "Hello World"

Latest revision as of 19:31, 19 January 2008

Redirect to: