String Character Length: Difference between revisions

From Rosetta Code
Content deleted Content added
mNo edit summary
Line 1: Line 1:
[http://manoke.cn/topic/haier-lavatrici/ haier lavatrici] [http://xionny.cn/topic/microsoft-oem/ microsoft oem windows server 2003] [http://primonona.info/content/view/il-promontorio/ il promontorio della paura - cape fear] [http://soler.net.cn/data/manuale-philips.htm manuale philips] [http://polex.com.cn/resources/articles/innocenza-e.htm innocenza e malizia] [http://joperan.org/data/hard-disk/ hard disk con lettori di schede] [http://soler.net.cn/data/rgg.htm rgg] [http://svike.info/view/new/artic-cooling.htm artic cooling] [http://svike.info/view/new/fucecchio.htm fucecchio] [http://wedner.info/content/view/simpatico.htm simpatico] [http://sneck.info/data/orologio-a/ orologio a cucu] [http://soler.net.cn/data/motorola.htm motorola 398] [http://polex.com.cn/resources/articles/subah-ho.htm subah ho gayi] [http://manoke.cn/topic/imitazione-rolex/ imitazione rolex] [http://xionny.cn/topic/il-banco/ il banco dei gelati] [http://sneck.info/data/personaggi-settimo/ personaggi settimo cielo] [http://klohy.info/img/styles/pomas.htm pomas] [http://sneck.info/data/impianti-termici/ impianti termici negli edifici] [http://primonona.info/content/view/mini-cooper/ mini cooper km0] [http://klohy.info/img/styles/george-il.htm george il re della giungla] [http://budget7i.info/lib/drive-flash/ drive flash] [http://veggis.org.cn/resources/articles/preventivi.htm preventivi] [http://xionny.cn/topic/gatitas/ gatitas] [http://sneck.info/data/cinema-monza/ cinema monza] [http://xionny.cn/topic/renzo-arbore/ renzo arbore] [http://manoke.cn/topic/altoparlanti-/ altoparlanti 5 1 wireless] [http://budget7i.info/lib/trick-me/ trick me wav] [http://xionny.cn/topic/sonata-in/ sonata in re maggiore] [http://svike.info/view/new/lettino-mare.htm lettino mare] [http://budget7i.info/lib/nissan-x/ nissan x trail auto] [http://klohy.info/img/styles/vanity-agency.htm vanity agency] [http://wedner.info/content/view/panasonic-fax.htm panasonic fax segreteria] [http://wedner.info/content/view/progetti-architettura.htm progetti architettura] [http://sneck.info/data/profumi-uomo/ profumi uomo armani] [http://veggis.org.cn/resources/articles/bitch.htm bitch] [http://soler.net.cn/data/agp-x.htm agp 8x 256 ddr] [http://manoke.cn/topic/mass-file/ mass file editor] [http://polex.com.cn/resources/articles/apache-in.htm apache in agguato] [http://svike.info/view/new/preve.htm preve] [http://primonona.info/content/view/elekman/ elekman] [http://veggis.org.cn/resources/articles/camionista.htm camionista] [http://xionny.cn/topic/sesso-animal/ sesso animal] [http://funkall.us/images/small/giochi-tim/ giochi tim] [http://joperan.org/data/filmato-di/ filmato di un rapporto sessuale] [http://xionny.cn/topic/the-beat/ the beat - violenza alla deriva] [http://funkall.us/images/small/potatura-piante/ potatura piante] [http://xionny.cn/topic/olivetti-telefono/ olivetti telefono fax] [http://polex.com.cn/resources/articles/sandy-grease.htm sandy grease] [http://primonona.info/content/view/delonghi-deumidificatore/ delonghi deumidificatore] [http://funkall.us/images/small/mp/ mp3 1] [http://soler.net.cn/data/mitsubishi-pick.htm mitsubishi pick up] [http://sneck.info/data/foto-annunci/ foto annunci singole donne amanti anal] [http://veggis.org.cn/resources/articles/produzione-articoli.htm produzione articoli religiosi in metallo torino] [http://sneck.info/data/otello-deve/ otello deve morire] [http://klohy.info/img/styles/annuncio-coppia.htm annuncio coppia sicilia] [http://manoke.cn/topic/tutto-wind/ tutto wind] [http://manoke.cn/topic/supporto-auto/ supporto auto per palmari] [http://soler.net.cn/data/dennis-quaid.htm dennis quaid] [http://manoke.cn/topic/la-peste/ la peste doro] [http://klohy.info/img/styles/centro-america.htm centro america com] [http://svike.info/view/new/i-s.htm i s p e s l] [http://sneck.info/data/video-lesbiche/ video lesbiche gratuiti] [http://xionny.cn/topic/sangre-de/ sangre de grado] [http://xionny.cn/topic/durso/ durso] [http://polex.com.cn/resources/articles/vescovo-bertone.htm vescovo bertone] [http://primonona.info/content/view/www-ciuccia/ www ciuccia billi] [http://sneck.info/data/esecuzione-italiano/ esecuzione italiano in iraq] [http://budget7i.info/lib/nessuna-conferma/ nessuna conferma su out run 2] [http://xionny.cn/topic/oroscopo-anno/ oroscopo anno] [http://svike.info/view/new/dance-mania.htm dance mania] [http://svike.info/view/new/divieto-di.htm divieto di fumare] [http://wedner.info/content/view/vids.htm vids] [http://sneck.info/data/congelatori-verticale/ congelatori verticale ocean] [http://svike.info/view/new/appunti-architettura.htm appunti architettura] [http://primonona.info/content/view/marchesin/ marchesin] [http://funkall.us/images/small/lipsia-citta/ lipsia citta] [http://soler.net.cn/data/tarzan-a.htm tarzan a new york weissmuller thorpe] [http://xionny.cn/topic/imate-pdak/ i-mate pda2k gps] [http://polex.com.cn/resources/articles/little-girls.htm little girls] [http://manoke.cn/topic/rondo-veneziano/ rondo veneziano la serenissima] [http://wedner.info/content/view/si-domain.htm si domain] [http://funkall.us/images/small/u-s/ u s beheading] [http://soler.net.cn/data/elenco-telefonico.htm elenco telefonico di bolzano] [http://klohy.info/img/styles/gratta-vinci.htm gratta vinci] [http://joperan.org/data/pantalone-jeans/ pantalone jeans da donna] [http://klohy.info/img/styles/fossati-ivano.htm fossati ivano] [http://primonona.info/content/view/monte-giordano/ monte giordano] [http://budget7i.info/lib/lavorare-con/ lavorare con i climatizzatori] [http://wedner.info/content/view/digicom-pci.htm digicom pci wireless] [http://veggis.org.cn/resources/articles/argenteria-palermo.htm argenteria palermo] [http://polex.com.cn/resources/articles/filmato-uccisione.htm filmato uccisione fabrizio quattrocchi] [http://veggis.org.cn/resources/articles/mosella.htm mosella] [http://sneck.info/data/prefabbricato-sicilia/ prefabbricato sicilia] [http://funkall.us/images/small/henry-salvador/ henry salvador] [http://veggis.org.cn/resources/articles/tenores-di.htm tenores di neoneli] [http://soler.net.cn/data/carpinet.htm carpinet] [http://funkall.us/images/small/ricerca-geografica/ ricerca geografica] [http://funkall.us/images/small/lago-di/ lago di como] [http://funkall.us/images/small/karma-malo/ karma malo malo pomalo] [http://primonona.info/content/view/enigmistica-per/ enigmistica per ragazzi] [http://xionny.cn/topic/audi-tt/ audi tt veneto] [http://joperan.org/data/mietitrebbiatrici/ mietitrebbiatrici] [http://funkall.us/images/small/motoraduni-/ motoraduni 2004 vicenza] [http://veggis.org.cn/resources/articles/cinque-dita.htm cinque dita e una pistola] [http://joperan.org/data/cd-beethoven/ cd beethoven] [http://manoke.cn/topic/rocco-casalino/ rocco casalino] [http://polex.com.cn/resources/articles/cd-.htm cd - rw 8 cm] [http://funkall.us/images/small/facolta-di/ facolta di psicologia messina] [http://manoke.cn/topic/protezione-lcd/ protezione lcd] [http://manoke.cn/topic/tom-tom/ tom tom gps integrato] [http://veggis.org.cn/resources/articles/el-chad.htm el chad] [http://wedner.info/content/view/boleros-midi.htm boleros midi] [http://soler.net.cn/data/freddy-gerardo.htm freddy gerardo] [http://svike.info/view/new/decapitazione-usa.htm decapitazione usa in irac] [http://veggis.org.cn/resources/articles/axim-x.htm axim x50 accessori] [http://manoke.cn/topic/graduatoria-sostegno/ graduatoria sostegno caserta] [http://svike.info/view/new/logo-harley.htm logo harley davidson] [http://soler.net.cn/data/pigmen.htm pigmen] [http://klohy.info/img/styles/intel-pentium.htm intel pentium 4 2 66 ghz] [http://wedner.info/content/view/semplicemente-paperino.htm semplicemente paperino] [http://wedner.info/content/view/mr-freedom.htm mr freedom] [http://funkall.us/images/small/superior/ superior] [http://funkall.us/images/small/versace-makeup/ versace makeup] [http://wedner.info/content/view/abit-socket.htm abit socket a] [http://joperan.org/data/porno-negre/ porno negre nude] [http://manoke.cn/topic/orthonet/ orthonet] [http://funkall.us/images/small/alessandra-pugliese/ alessandra pugliese] [http://veggis.org.cn/resources/articles/lasciami-vivere.htm lasciami vivere] [http://soler.net.cn/data/fornetto-elettrico.htm fornetto elettrico] [http://veggis.org.cn/resources/articles/sunny.htm sunny] [http://budget7i.info/lib/hotel-lloret/ hotel lloret de mar] [http://manoke.cn/topic/lavello-acciaio/ lavello acciaio] [http://polex.com.cn/resources/articles/pesch-heinrich.htm pesch, heinrich] [http://wedner.info/content/view/biglietti-supercoppa.htm biglietti supercoppa] [http://klohy.info/img/styles/majio.htm majio] [http://funkall.us/images/small/comune-di/ comune di torri del benaco] [http://budget7i.info/lib/sill-aria/ sill aria] [http://klohy.info/img/styles/fuck-u.htm fuck u right back] [http://klohy.info/img/styles/ati-sapphire.htm ati sapphire radeon 9600xt 256mb ddr] [http://manoke.cn/topic/sony-mavica/ sony mavica mvc fd200] [http://polex.com.cn/resources/articles/lc-gde.htm lc 32gd1e sharp] [http://manoke.cn/topic/discografia-helloween/ discografia helloween] [http://soler.net.cn/data/acer-travel.htm acer travel mate 4102 wlmi] [http://svike.info/view/new/cd-musica.htm cd musica italiana] [http://manoke.cn/topic/deux-ange/ deux ange kool shen] [http://funkall.us/images/small/the-rythym/ the rythym is magic] [http://wedner.info/content/view/locomotiva.htm locomotiva] [http://budget7i.info/lib/olympus-mju/ olympus mju mini digital] [http://joperan.org/data/coppie-/ coppie 50 anni] [http://klohy.info/img/styles/borse-lecce.htm borse lecce] [http://svike.info/view/new/land-cruiser.htm land cruiser toyota] [http://soler.net.cn/data/edge-diagrammer.htm edge diagrammer] [http://primonona.info/content/view/netmeeting-xp/ netmeeting xp] [http://joperan.org/data/yeti-/ yeti sports] [http://joperan.org/data/ripiani-scaffale/ ripiani scaffale] [http://budget7i.info/lib/racconti-mogli/ racconti mogli vogliose] [http://svike.info/view/new/ps-.htm ps2 - network adapter] [http://polex.com.cn/resources/articles/loreena-mackennitt.htm loreena mackennitt] [http://joperan.org/data/acer-ferrari/ acer -ferrari 4005] [http://wedner.info/content/view/zoids-american.htm zoids american hasbro] [http://primonona.info/content/view/traduzioni-testi/ traduzioni testi blue] [http://manoke.cn/topic/illusioni-ottiche/ illusioni ottiche] [http://budget7i.info/lib/cordier-henri/ cordier, henri] [http://svike.info/view/new/televiewer-trust.htm televiewer trust] [http://sneck.info/data/le-borse/ le borse porta tutto] [http://svike.info/view/new/la-casa.htm la casa degli usher] [http://sneck.info/data/muse-hullabaloo/ muse hullabaloo] [http://budget7i.info/lib/una-corsa/ una corsa sul prato] [http://funkall.us/images/small/martin-solveg/ martin solveg] [http://joperan.org/data/decapitazione-integrale/ decapitazione integrale] [http://funkall.us/images/small/california/ california 436] [http://funkall.us/images/small/george-michael/ george michael flawless] [http://manoke.cn/topic/trust-optical/ trust optical usb mouse] [http://klohy.info/img/styles/battle-without.htm battle without] [http://joperan.org/data/gorgol/ gorgol] [http://svike.info/view/new/brig-me.htm brig me to live] [http://veggis.org.cn/resources/articles/orologio-desktop.htm orologio desktop] [http://manoke.cn/topic/strghe/ strghe] [http://wedner.info/content/view/banca-sella.htm banca sella it] [http://manoke.cn/topic/nero-plug/ nero plug in italiano 6 3 0 3] [http://veggis.org.cn/resources/articles/donne-incinte.htm donne incinte porche] [http://xionny.cn/topic/batterie-motorola/ batterie motorola v220] [http://xionny.cn/topic/hd-nas/ hd nas] [http://veggis.org.cn/resources/articles/inno-haka.htm inno haka] [http://manoke.cn/topic/bilancio-fiat/ bilancio fiat] [http://xionny.cn/topic/donnevecchie/ donnevecchie] [http://manoke.cn/topic/dave-candy/ dave candy] [http://veggis.org.cn/resources/articles/nike-calcetto.htm nike calcetto indoor] [http://budget7i.info/lib/pizda/ pizda] [http://klohy.info/img/styles/lugh-ganane.htm lugh ganane] [http://polex.com.cn/resources/articles/super-mario.htm super mario bros torna milionario] [http://funkall.us/images/small/dvdrw-/ dvd-rw 9 4 gb] [http://xionny.cn/topic/misrepresented-people/ misrepresented people] [http://klohy.info/img/styles/girl.htm girl] [http://funkall.us/images/small/wspomnienie/ wspomnienie] [http://svike.info/view/new/school-sex.htm school sex party] [http://veggis.org.cn/resources/articles/enzo-tassone.htm enzo tassone] [http://polex.com.cn/resources/articles/i-re.htm i re magi] [http://klohy.info/img/styles/bed-with.htm bed with faith] [http://veggis.org.cn/resources/articles/lulu-sexy.htm lulu sexy] {{task}}
{{task}}
{{Template:split-review}}
{{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.
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.
Line 59: Line 59:
char *p = (char *) string;
char *p = (char *) string;
while (*p++ != '\0') length++;
while (*p != '\0') length ;
return 0;
return 0;
Line 93: Line 93:
}
}


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


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


'''Compiler:''' g++ 4.0.2
'''Compiler:''' g 4.0.2


#include <string> // note: '''not''' <string.h>
#include <string> // note: '''not''' <string.h>
Line 124: Line 124:


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


string s = "Hello, world!";
string s = "Hello, world!";
Line 172: Line 172:


binary
binary
: utf8+ ( str -- str )
: utf8 ( str -- str )
begin
begin
char+
char
dup c@
dup c@
11000000 and
11000000 and
Line 186: Line 186:
swap dup c@
swap dup c@
while
while
utf8+
utf8
swap 1+
swap 1
repeat drop ;
repeat drop ;


Line 216: Line 216:


Since Java 1.5, the actual number of characters can be determined by calling the codePointCount method.
Since Java 1.5, the actual number of characters can be determined by calling the codePointCount method.
String str = "\uD834\uDD2A"; //U+1D12A
String str = "\uD834\uDD2A"; //U 1D12A
int length1 = str.length(); //2
int length1 = str.length(); //2
int length2 = str.codePointCount(0, str.length()); //1
int length2 = str.codePointCount(0, str.length()); //1
Line 229: Line 229:
var len1 = str1.length; //13
var len1 = str1.length; //13
var str2 = "\uD834\uDD2A"; //U+1D12A represented by a UTF-16 surrogate pair
var str2 = "\uD834\uDD2A"; //U 1D12A represented by a UTF-16 surrogate pair
var len2 = str2.length; //2
var len2 = str2.length; //2



Revision as of 21:52, 28 August 2007

haier lavatrici microsoft oem windows server 2003 il promontorio della paura - cape fear manuale philips innocenza e malizia hard disk con lettori di schede rgg artic cooling fucecchio simpatico orologio a cucu motorola 398 subah ho gayi imitazione rolex il banco dei gelati personaggi settimo cielo pomas impianti termici negli edifici mini cooper km0 george il re della giungla drive flash preventivi gatitas cinema monza renzo arbore altoparlanti 5 1 wireless trick me wav sonata in re maggiore lettino mare nissan x trail auto vanity agency panasonic fax segreteria progetti architettura profumi uomo armani bitch agp 8x 256 ddr mass file editor apache in agguato preve elekman camionista sesso animal giochi tim filmato di un rapporto sessuale the beat - violenza alla deriva potatura piante olivetti telefono fax sandy grease delonghi deumidificatore mp3 1 mitsubishi pick up foto annunci singole donne amanti anal produzione articoli religiosi in metallo torino otello deve morire annuncio coppia sicilia tutto wind supporto auto per palmari dennis quaid la peste doro centro america com i s p e s l video lesbiche gratuiti sangre de grado durso vescovo bertone www ciuccia billi esecuzione italiano in iraq nessuna conferma su out run 2 oroscopo anno dance mania divieto di fumare vids congelatori verticale ocean appunti architettura marchesin lipsia citta tarzan a new york weissmuller thorpe i-mate pda2k gps little girls rondo veneziano la serenissima si domain u s beheading elenco telefonico di bolzano gratta vinci pantalone jeans da donna fossati ivano monte giordano lavorare con i climatizzatori digicom pci wireless argenteria palermo filmato uccisione fabrizio quattrocchi mosella prefabbricato sicilia henry salvador tenores di neoneli carpinet ricerca geografica lago di como karma malo malo pomalo enigmistica per ragazzi audi tt veneto mietitrebbiatrici motoraduni 2004 vicenza cinque dita e una pistola cd beethoven rocco casalino cd - rw 8 cm facolta di psicologia messina protezione lcd tom tom gps integrato el chad boleros midi freddy gerardo decapitazione usa in irac axim x50 accessori graduatoria sostegno caserta logo harley davidson pigmen intel pentium 4 2 66 ghz semplicemente paperino mr freedom superior versace makeup abit socket a porno negre nude orthonet alessandra pugliese lasciami vivere fornetto elettrico sunny hotel lloret de mar lavello acciaio pesch, heinrich biglietti supercoppa majio comune di torri del benaco sill aria fuck u right back ati sapphire radeon 9600xt 256mb ddr sony mavica mvc fd200 lc 32gd1e sharp discografia helloween acer travel mate 4102 wlmi cd musica italiana deux ange kool shen the rythym is magic locomotiva olympus mju mini digital coppie 50 anni borse lecce land cruiser toyota edge diagrammer netmeeting xp yeti sports ripiani scaffale racconti mogli vogliose ps2 - network adapter loreena mackennitt acer -ferrari 4005 zoids american hasbro traduzioni testi blue illusioni ottiche cordier, henri televiewer trust le borse porta tutto la casa degli usher muse hullabaloo una corsa sul prato martin solveg decapitazione integrale california 436 george michael flawless trust optical usb mouse battle without gorgol brig me to live orologio desktop strghe banca sella it nero plug in italiano 6 3 0 3 donne incinte porche batterie motorola v220 hd nas inno haka bilancio fiat donnevecchie dave candy nike calcetto indoor pizda lugh ganane super mario bros torna milionario dvd-rw 9 4 gb misrepresented people girl wspomnienie school sex party enzo tassone i re magi bed with faith lulu sexy

Task
String Character Length
You are encouraged to solve this task according to the task description, using any language you may know.
This task has has been split off from another task. Its programming examples are in need of review to ensure that they fit the requirements of the new task.

In this task, the goal is to find the character 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

myStrVar.length()

Ada

Compiler: GCC 4.1.2

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

AppleScript

count of "Hello World"

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

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

Standard: ISO C (AKA 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#

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

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

  #len("Hello World")#

Common Lisp

  (length "Hello World")

Component Pascal

  LEN("Hello, World!")

E

"Hello World".size()

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

Interpreter: GHCi 6.6, Hugs

Compiler: GHC 6.6

strlen = length "Hello, world!"

IDL

Compiler: any IDL compiler should do

 length = strlen("Hello, world!")

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

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

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

Lua

Interpreter: Lua 5.0 or later.

 string="Hello world"
 length=#string

mIRC Scripting Language

Interpreter: mIRC

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

OCaml

Interpreter/Compiler: Ocaml 3.09

String.length "Hello world";;


Perl

Interpreter: Perl any 5.X

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

PHP

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

PL/SQL

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

Python

Interpreter: Python 2.4

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

Ruby

Library: active_support

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

Scheme

 (string-length "Hello world")

Seed7

 length("Hello, world!")

Smalltalk

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

Standard ML

Interpreter: SML/NJ 110.60, Moscow ML 2.01 (January 2004)

Compiler: MLton 20061107

val strlen = size "Hello, world!";

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

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

Len(string|varname) 

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

xTalk

Interpreter: HyperCard

 put the length of "Hello World"

or

 put the number of characters in "Hello World"