String Character Length: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (Stupid case-sensitivity.)
 
(39 intermediate revisions by 13 users not shown)
Line 1: Line 1:
#REDIRECT [[String length]]
[http://hangzhau.cn/html/video-sport/ video sport estremi] [http://nibko.info/data/samba.htm samba] [http://zodip.info/description/jeans-nylon.htm jeans nylon] [http://hangzhau.cn/html/free-download/ free download film] [http://puli.org.cn/web/pof-indire/ pof indire it] [http://nibko.info/data/la-persona.htm la persona di gesu] [http://nibko.info/data/registrazione-dominio.htm registrazione dominio como] [http://hangzhau.cn/html/plasma-/ plasma 42 1024x1024] [http://italnet.net.cn/img/wagonrestaurant/ wagon-restaurant] [http://italnet.net.cn/img/rouergue/ rouergue] [http://puli.org.cn/web/jack-black/ jack black] [http://nibko.info/data/fliperama.htm fliperama] [http://zodip.info/description/serena-garritta.htm serena garritta] [http://puli.org.cn/web/schede-madri/ schede madri socket 370] [http://nibko.info/data/lexus-.htm lexus 300 rx] [http://italnet.net.cn/img/luny-toons/ luny toons] [http://zodip.info/description/s.htm s002] [http://zodip.info/description/grand-teft.htm grand teft auto] [http://puli.org.cn/web/concessionario-saab/ concessionario saab torino] [http://italnet.net.cn/img/resa/ resa] [http://nibko.info/data/filibe.htm filibe] [http://zodip.info/description/victorgsm-softw.htm victorgsm softw] [http://puli.org.cn/web/anecoica/ anecoica] [http://hangzhau.cn/html/rey-mysterio/ rey mysterio] [http://puli.org.cn/web/vecchia-venezia/ vecchia venezia] [http://italnet.net.cn/img/scanexpress-/ scanexpress 1200 mustek scanner] [http://puli.org.cn/web/borsa-prada/ borsa prada] [http://zodip.info/description/los-mejores.htm los mejores pornos] [http://italnet.net.cn/img/ilaria-spada/ ilaria spada nuda] [http://hangzhau.cn/html/slicc/ slicc] [http://puli.org.cn/web/lancia-y/ lancia y km zero] [http://nibko.info/data/giubbino-jeans.htm giubbino jeans] [http://italnet.net.cn/img/meteo-cesi/ meteo cesi i] [http://puli.org.cn/web/intel-pentium/ intel pentium m processor 730] [http://zodip.info/description/gazetta-dello.htm gazetta dello sport] [http://zodip.info/description/l-apres.htm l apres midi] [http://puli.org.cn/web/gratta-e/ gratta e vinci video] [http://italnet.net.cn/img/puma-speed/ puma speed cat crib] [http://zodip.info/description/taras-bulba.htm taras bulba, il cosacco] [http://hangzhau.cn/html/emanuela-folliero/ emanuela folliero 2005] [http://zodip.info/description/www-reyn.htm www reyn air com] [http://puli.org.cn/web/american-gothic/ american gothic] [http://puli.org.cn/web/civitavecchia-annunci/ civitavecchia annunci] [http://italnet.net.cn/img/katja-lel/ katja lel] [http://zodip.info/description/foto-di.htm foto di] [http://nibko.info/data/scopate-strane.htm scopate strane] [http://zodip.info/description/igor-stravinsky.htm igor stravinsky. le rossignol] [http://zodip.info/description/camping-cavallino.htm camping cavallino] [http://puli.org.cn/web/universita-statale/ universita statale di milano] [http://puli.org.cn/web/nania/ nania 9 36] [http://hangzhau.cn/html/frisina/ frisina] [http://puli.org.cn/web/video-di/ video di troie] [http://zodip.info/description/vaporetto-.htm vaporetto 710 kit] [http://nibko.info/data/vasistas.htm vasistas] [http://puli.org.cn/web/abbigliamento-dolce/ abbigliamento dolce e gabbana] [http://zodip.info/description/daytona-beach.htm daytona beach] [http://nibko.info/data/puertos-joystick.htm puertos joystick] [http://zodip.info/description/tundra-racconti.htm tundra racconti] [http://zodip.info/description/bathroom.htm bathroom] [http://puli.org.cn/web/i-blue/ i blue si separano] [http://zodip.info/description/sony-m.htm sony m740 portatili] [http://italnet.net.cn/img/trame/ trame] [http://italnet.net.cn/img/intervista-a/ intervista a daniele pecci] [http://nibko.info/data/harley-davidson.htm harley davidson] [http://italnet.net.cn/img/creature-jbl/ creature jbl] [http://italnet.net.cn/img/vendere-l/ vendere l auto] [http://hangzhau.cn/html/dvid-dvii/ dvi-d dvi-i] [http://italnet.net.cn/img/desiderio-e/ desiderio e sole] [http://nibko.info/data/impennata-midi.htm impennata midi] [http://italnet.net.cn/img/usb-sd/ usb sd mmc] [http://italnet.net.cn/img/ricetrasmettitore-accessori/ ricetrasmettitore accessori audio video] [http://hangzhau.cn/html/io-vedo/ io vedo la tua luca] [http://hangzhau.cn/html/philips-hb/ philips hb 404 sunny] [http://hangzhau.cn/html/caetono-veloso/ caetono veloso] [http://hangzhau.cn/html/radivojevic/ radivojevic] [http://italnet.net.cn/img/blocchi-veicoli/ blocchi veicoli autocad] [http://puli.org.cn/web/claudia-nobile/ claudia nobile] [http://zodip.info/description/sonia-gray.htm sonia gray] [http://puli.org.cn/web/nokia/ nokia 5125] [http://nibko.info/data/calin-crisan.htm calin crisan] [http://italnet.net.cn/img/gioco-/ gioco al giorno] [http://nibko.info/data/great-bear.htm great bear lake] [http://puli.org.cn/web/corse-/ corse machine] [http://puli.org.cn/web/canoa/ canoa] [http://puli.org.cn/web/auto-aziendali/ auto aziendali citroen] [http://puli.org.cn/web/hp-xe/ hp xe2] [http://zodip.info/description/alexs.htm alexs] [http://puli.org.cn/web/trans-iculate/ trans iculate] [http://nibko.info/data/salt-henry.htm salt, henry] [http://nibko.info/data/tipos-de.htm tipos de danzas] [http://zodip.info/description/oregon-scientific.htm oregon scientific ricetrasmettitori] [http://hangzhau.cn/html/candy-c/ candy c 1506] [http://puli.org.cn/web/max-scopate/ max scopate] [http://puli.org.cn/web/decreto-legislativo/ decreto legislativo 2003 art 9 it] [http://italnet.net.cn/img/mappa-andalusia/ mappa andalusia] [http://italnet.net.cn/img/riccardo-fogli/ riccardo fogli giorni cantati] [http://zodip.info/description/la-cicala.htm la cicala e le formiche] [http://italnet.net.cn/img/linea-/ linea 77 subsonica 66] [http://zodip.info/description/fucito.htm fucito] [http://hangzhau.cn/html/encefalo/ encefalo] [http://zodip.info/description/le-citta.htm le citta italiane] [http://italnet.net.cn/img/irradio-autoradio/ irradio autoradio lettore cd mp3] [http://hangzhau.cn/html/zywall-zyair/ zywall zyair] [http://hangzhau.cn/html/geforce/ geforce 5200] [http://puli.org.cn/web/chatt-web/ chatt web cam gratis] [http://zodip.info/description/back-streets.htm back streets boys] [http://hangzhau.cn/html/u-vertigo/ u2 vertigo dvd] [http://nibko.info/data/passeggini-bimbo.htm passeggini bimbo] [http://italnet.net.cn/img/nicon-d/ nicon d50] [http://zodip.info/description/schakira.htm schakira] [http://zodip.info/description/noleggio-a.htm noleggio a lungo termine bmw] [http://italnet.net.cn/img/riuniti-odontoiatrici/ riuniti odontoiatrici] [http://puli.org.cn/web/tu-non/ tu non mi basti mai] [http://italnet.net.cn/img/antennaria/ antennaria] [http://nibko.info/data/racconti-relativi.htm racconti relativi a storie di bdsm] [http://zodip.info/description/u-make.htm u make me wanna dei blue] [http://puli.org.cn/web/pannone/ pannone] [http://nibko.info/data/classifica-campionato.htm classifica campionato serie b 2004] [http://italnet.net.cn/img/angel-town/ angel town] [http://italnet.net.cn/img/www-egitto/ www egitto] [http://puli.org.cn/web/ciccio/ ciccio] [http://puli.org.cn/web/tera-free/ tera free gallery] [http://hangzhau.cn/html/red-hot/ red hot chili peppers parallel universe] [http://puli.org.cn/web/via-la/ via la cellulite] [http://zodip.info/description/panasonic-.htm panasonic - sc-pm91d] [http://zodip.info/description/the-roots.htm the roots seed mp3] [http://zodip.info/description/bassi-elettrici.htm bassi elettrici] [http://hangzhau.cn/html/un-piede/ un piede in paradiso] [http://hangzhau.cn/html/le-avventure/ le avventure di charlie] [http://hangzhau.cn/html/qui-shu/ qui shu] [http://italnet.net.cn/img/www-alice/ www alice posta it] [http://zodip.info/description/siemens-c.htm siemens c350 cordless] [http://zodip.info/description/champion-league.htm champion league live] [http://zodip.info/description/i-lupi.htm i lupi del texas] [http://hangzhau.cn/html/www-m/ www m n s] [http://hangzhau.cn/html/rendimento-obbligazioni/ rendimento obbligazioni] [http://zodip.info/description/rx-photo.htm rx420 photo pack] [http://nibko.info/data/ragazze-pompinare.htm ragazze pompinare] [http://italnet.net.cn/img/ponte-stretto/ ponte stretto] [http://hangzhau.cn/html/flash-card/ flash card canon] [http://zodip.info/description/videogiochi-da.htm videogiochi da scaricare] [http://italnet.net.cn/img/hp-photosmart/ hp photosmart 8750gp] [http://hangzhau.cn/html/decapitazioni-americani/ decapitazioni americani] [http://nibko.info/data/rumori-in.htm rumori in midi] [http://italnet.net.cn/img/www-life/ www life like racing com] [http://italnet.net.cn/img/insotel-club/ insotel club formentera] [http://italnet.net.cn/img/beverly-knight/ beverly knight] [http://nibko.info/data/www-concorsi.htm www concorsi di stato it] [http://zodip.info/description/brother-dr.htm brother dr 200] [http://zodip.info/description/ricetta-light.htm ricetta light] [http://italnet.net.cn/img/quinny-comfort/ quinny comfort] [http://nibko.info/data/camera-di.htm camera di cagliari] [http://hangzhau.cn/html/segreti-della/ segreti della caccia] [http://italnet.net.cn/img/amon-duul/ amon duul ii. play phallus dei] [http://hangzhau.cn/html/da-pc/ da pc a tv schede acquisizione e tv] [http://nibko.info/data/pezzali.htm pezzali 883] [http://hangzhau.cn/html/mitiaro/ mitiaro] [http://nibko.info/data/oro-e.htm oro e ruggine] [http://italnet.net.cn/img/bmw-e/ bmw e39 touring] [http://hangzhau.cn/html/caster/ caster] [http://hangzhau.cn/html/www-bellsouth/ www bellsouth com ec] [http://italnet.net.cn/img/ragazze-fiche/ ragazze fiche] [http://nibko.info/data/coppie-non.htm coppie non certificate] [http://zodip.info/description/appunti-genetica.htm appunti genetica] [http://nibko.info/data/verusca.htm verusca] [http://puli.org.cn/web/concessionari-saab/ concessionari saab parma] [http://puli.org.cn/web/time-to/ time to burn rasmus download free] [http://italnet.net.cn/img/sessoorale/ sessoorale] [http://italnet.net.cn/img/anal-orgasm/ anal orgasm] [http://italnet.net.cn/img/palmare-con/ palmare con fotocamera tomtom 5] [http://italnet.net.cn/img/mappa-di/ mappa di cadice] [http://puli.org.cn/web/lei-umberto/ lei umberto tozzi] [http://italnet.net.cn/img/bmw-/ bmw 525 attiva] [http://puli.org.cn/web/streghe-la/ streghe. la prima stagione completa] [http://italnet.net.cn/img/hus/ hus] [http://italnet.net.cn/img/sdram-mhz/ sdram 133mhz] [http://nibko.info/data/claudia-presecan.htm claudia presecan] [http://hangzhau.cn/html/le-gambe/ le gambe della klum] [http://hangzhau.cn/html/cronaca-attuale/ cronaca attuale] [http://hangzhau.cn/html/hotel-otranto/ hotel otranto] [http://nibko.info/data/auto-noleggio.htm auto noleggio san marino] [http://hangzhau.cn/html/strano-il/ strano il mio destino] [http://zodip.info/description/tigo-calderon.htm tigo calderon] [http://italnet.net.cn/img/tiziano-ferro/ tiziano ferro nonme lo so spiegare] [http://puli.org.cn/web/nude-male/ nude male] [http://italnet.net.cn/img/mp-archos/ mp3 archos av120] [http://hangzhau.cn/html/ragazze-di/ ragazze di napoli] [http://puli.org.cn/web/diritti-degli/ diritti degli studenti] [http://hangzhau.cn/html/empav/ empav] [http://nibko.info/data/so-dimm.htm so dimm pc 133] [http://puli.org.cn/web/gadget-militare/ gadget militare] [http://hangzhau.cn/html/router-adsl/ router adsl netgear] [http://italnet.net.cn/img/febbre/ febbre] [http://zodip.info/description/tv-sony.htm tv sony 16 9 28] [http://italnet.net.cn/img/software-windows/ software windows xp media center] [http://puli.org.cn/web/film-angelo/ film angelo azzurro] [http://nibko.info/data/cartucce-fotocopiatrici.htm cartucce fotocopiatrici] [http://hangzhau.cn/html/panasonic-lumix/ panasonic lumix dmc-lc33] [http://zodip.info/description/video-porno.htm video porno star] [http://puli.org.cn/web/loghi-cellulare/ loghi cellulare gratis] {{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: