String Byte Length: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (Stupid case-sensitivity.)
 
(48 intermediate revisions by 13 users not shown)
Line 1: Line 1:
#REDIRECT [[String length]]
[http://chaba.info/umts-cellulari/ umts cellulari samsung] [http://davte.info/library/html/dr-alte.htm dr alte holz] [http://bloprofeldi.info/lib/background-colours.htm background colours] [http://kinunia.cn/conaju.htm conaju] [http://kinunia.cn/wem-j.htm wem j] [http://helmed.info/topic/yu-gi/ yu gi ho gioco da scaricare] [http://saibso.org/riobamba.htm riobamba] [http://helmed.info/topic/la-maledizione/ la maledizione della prima luna il disco] [http://ustall.org/web/elettrostimolatore-babyliss.htm elettrostimolatore babyliss] [http://bloprofeldi.info/lib/antifumo.htm antifumo] [http://kinunia.cn/trio-chicco.htm trio chicco autofix] [http://nobinters.org/then-servant.htm then servant] [http://bloprofeldi.info/lib/vino-giordano.htm vino giordano] [http://helmed.info/topic/thesis-diesel/ thesis diesel] [http://amohseni.info/img/styles/sito-telefonia/ sito telefonia] [http://psisemiya.com/images/small/thoitrang/ thoitrang] [http://kinunia.cn/macromedia-flash.htm macromedia flash] [http://ashythro.info/library/html/www-amiloidosi/ www amiloidosi it] [http://ustall.org/web/marcello-fondato.htm marcello fondato] [http://davte.info/library/html/il-killer.htm il killer - tactical assassin] [http://helmed.info/topic/kawasaki-zx/ kawasaki zx 6r] [http://psisemiya.com/images/small/bmw-compact/ bmw compact] [http://psisemiya.com/images/small/ferrar/ ferrar] [http://psisemiya.com/images/small/paola-perego/ paola perego foto] [http://bloprofeldi.info/lib/remington-hc.htm remington hc363] [http://nobinters.org/sottoveste-che.htm sottoveste che passione] [http://psisemiya.com/images/small/la-ginestra/ la ginestra] [http://helmed.info/topic/terorema/ terorema] [http://helmed.info/topic/lavatrici-/ lavatrici 33 cm] [http://ustall.org/web/adsl-firewall.htm adsl2 firewall router] [http://davte.info/library/html/online-personal.htm online personal ads] [http://bloprofeldi.info/lib/la-grande.htm la grande fuga] [http://psisemiya.com/images/small/dutilleux/ dutilleux] [http://chaba.info/venezia-parigi/ venezia parigi] [http://nobinters.org/midi-gigi.htm midi gigi finizio] [http://nobinters.org/nuova-mercedes.htm nuova mercedes 320 s diesel auto nuove] [http://amohseni.info/img/styles/gestion-privee/ gestion privee] [http://chaba.info/clearvue-worksheet/ clearvue worksheet] [http://saibso.org/focus-c.htm focus c max 1.8] [http://nobinters.org/u-s.htm u s beheading] [http://bloprofeldi.info/lib/hub-base.htm hub 100base fx] [http://chaba.info/agri/ agri 3] [http://kinunia.cn/hd-seagate.htm hd seagate 160gb] [http://ustall.org/web/parnassia.htm parnassia] [http://ustall.org/web/www-ibox.htm www ibox] [http://nobinters.org/shemale-hentai.htm shemale hentai] [http://helmed.info/topic/che-fico/ che fico] [http://saibso.org/anna-dei.htm anna dei mille giorni] [http://kinunia.cn/sbavatura.htm sbavatura] [http://bloprofeldi.info/lib/luscita.htm luscita] [http://chaba.info/eos-d/ eos 20d corpo] [http://chaba.info/minegold/ minegold] [http://davte.info/library/html/barraca-destroy.htm barraca destroy] [http://ustall.org/web/siena-.htm siena 19 atc] [http://amohseni.info/img/styles/myst-iv/ myst iv in un filmato] [http://saibso.org/bacilos.htm bacilos] [http://nobinters.org/annuncio-affitti.htm annuncio affitti ferrara] [http://ustall.org/web/testo-on.htm testo on my knees] [http://davte.info/library/html/la-rush.htm la rush in foto e video] [http://psisemiya.com/images/small/isoleeolie/ isoleeolie] [http://nobinters.org/aix-en.htm aix en provence pierre e t vacance] [http://psisemiya.com/images/small/keira-knightly/ keira knightly naked] [http://bloprofeldi.info/lib/heuring.htm heuring] [http://chaba.info/te-comere/ te comere a besos] [http://psisemiya.com/images/small/breed/ breed] [http://helmed.info/topic/vacanza-puglia/ vacanza puglia residence] [http://chaba.info/mns-messenger/ mns messenger] [http://ustall.org/web/hety.htm hety] [http://bloprofeldi.info/lib/love-is.htm love is blue marty robbins] [http://helmed.info/topic/nobile/ nobile] [http://chaba.info/ef-mm/ ef 600mm] [http://davte.info/library/html/kazem.htm kazem] [http://helmed.info/topic/diminuiscono-le/ diminuiscono le vendite hardware in usa] [http://psisemiya.com/images/small/air-classic/ air classic bw] [http://davte.info/library/html/black.htm black2] [http://ustall.org/web/gps-nokia.htm gps nokia 9300] [http://saibso.org/stampante-a.htm stampante a3 ethernet colori] [http://chaba.info/intimo-dolce/ intimo dolce e gabbana uomo] [http://helmed.info/topic/ricevitori-satellitari/ ricevitori satellitari 12v] [http://chaba.info/juve-schifo/ juve schifo] [http://ustall.org/web/hotel-mediterraneo.htm hotel mediterraneo] [http://ashythro.info/library/html/the-sheltering/ the sheltering sky] [http://davte.info/library/html/epson-s.htm epson s050190] [http://chaba.info/canzoni-napoletana/ canzoni napoletana] [http://davte.info/library/html/nvidia-fx.htm nvidia fx330] [http://davte.info/library/html/pellegrini-spa.htm pellegrini spa] [http://ustall.org/web/xerox-cx.htm xerox 480cx] [http://bloprofeldi.info/lib/little-wings.htm little wings] [http://helmed.info/topic/batteria-ericsson/ batteria ericsson a1018s] [http://chaba.info/lcd-/ lcd 19 12ms] [http://davte.info/library/html/more-than.htm more than world] [http://helmed.info/topic/sandri/ sandri] [http://saibso.org/vestiti-di.htm vestiti di alessandra] [http://psisemiya.com/images/small/disturbed-forsaken/ disturbed forsaken] [http://amohseni.info/img/styles/serena-brande/ serena brande fratello] [http://psisemiya.com/images/small/denel/ denel] [http://chaba.info/blowjobs/ blowjobs] [http://ashythro.info/library/html/dvd-recorder/ dvd recorder vcr sharp] [http://saibso.org/macchina-fotografica.htm macchina fotografica on line] [http://nobinters.org/paint.htm paint] [http://nobinters.org/memoria-fotocamera.htm memoria fotocamera olympus] [http://saibso.org/www-frau.htm www frau it] [http://saibso.org/doslocos.htm doslocos] [http://saibso.org/pensiero-socialista.htm pensiero socialista comunista] [http://davte.info/library/html/rino-gaetano.htm rino gaetano mid] [http://saibso.org/pinna-da.htm pinna da nuoto] [http://davte.info/library/html/auto-noleggio.htm auto noleggio besate] [http://ustall.org/web/progettazione-macchina.htm progettazione macchina] [http://chaba.info/photostudio/ photostudio] [http://amohseni.info/img/styles/titan/ titan] [http://kinunia.cn/sassabanek.htm sassabanek] [http://kinunia.cn/clip-art.htm clip art di matrimonio] [http://amohseni.info/img/styles/la-rush/ l.a. rush] [http://bloprofeldi.info/lib/calzature-armani.htm calzature armani] [http://kinunia.cn/prada-abiti.htm prada abiti uomo] [http://ustall.org/web/copertina-cd.htm copertina cd dragostea haiducii] [http://davte.info/library/html/salute-fisica.htm salute fisica] [http://ustall.org/web/srilanka.htm srilanka] [http://chaba.info/collegio-sindacale/ collegio sindacale nella corporate] [http://davte.info/library/html/bridget-jones.htm bridget jones 2] [http://saibso.org/pian-vigne.htm pian vigne] [http://bloprofeldi.info/lib/codici-di.htm codici di acceso tps] [http://ustall.org/web/mapa-de.htm mapa de espana] [http://kinunia.cn/www-cerbone.htm www cerbone moto it] [http://amohseni.info/img/styles/esame-avvocato/ esame avvocato 2003 messina] [http://ashythro.info/library/html/marianna-jurcova/ marianna jurcova] [http://bloprofeldi.info/lib/oakley-monster.htm oakley monster dog] [http://ustall.org/web/dsc-h.htm dsc h1 sony] [http://davte.info/library/html/toshiba-satellite.htm toshiba satellite 760] [http://chaba.info/jvc-car/ jvc car audio] [http://psisemiya.com/images/small/guta-nicolae/ guta nicolae] [http://davte.info/library/html/atomik-kitten.htm atomik kitten] [http://davte.info/library/html/cartina-geografica.htm cartina geografica francia] [http://helmed.info/topic/cartoline-di/ cartoline di napoli] [http://nobinters.org/saintmichel.htm saint-michel] [http://psisemiya.com/images/small/infineon/ infineon 512] [http://ustall.org/web/puma-uomo.htm puma uomo blu] [http://bloprofeldi.info/lib/no-sikiriki.htm no sikiriki] [http://amohseni.info/img/styles/radeon-x/ radeon x800 pro 256 mb] [http://amohseni.info/img/styles/miss-nude/ miss nude] [http://psisemiya.com/images/small/toshiba-wlp/ toshiba 37wl56p] [http://ashythro.info/library/html/mai-sola/ mai sola] [http://amohseni.info/img/styles/liviu/ liviu] [http://saibso.org/copay-secondo.htm copay secondo] [http://kinunia.cn/stay-tommy.htm stay tommy vee] [http://bloprofeldi.info/lib/londra-di.htm londra di notte] [http://psisemiya.com/images/small/left-outsdie/ left outsdie alone] [http://helmed.info/topic/uruguaiana/ uruguaiana] [http://saibso.org/positano-alberghi.htm positano alberghi e hotel] [http://chaba.info/peugeot/ peugeot 106 1.1] [http://psisemiya.com/images/small/babilonia/ babilonia] [http://helmed.info/topic/attrezzatura-giardinaggio/ attrezzatura giardinaggio] [http://ustall.org/web/embalaje.htm embalaje] [http://psisemiya.com/images/small/toshiba-notebook/ toshiba notebook] [http://saibso.org/chingling.htm ching-ling] [http://ustall.org/web/porcate-assolute.htm porcate assolute] [http://amohseni.info/img/styles/tv-color/ tv color 20 pollici] [http://helmed.info/topic/il-cervello/ il cervello] [http://ashythro.info/library/html/veicoli-ed/ veicoli ed attrezzature] [http://bloprofeldi.info/lib/all-in.htm all in one computer] [http://amohseni.info/img/styles/dialoghi-in/ dialoghi in italiano del musical grease] [http://amohseni.info/img/styles/philips-sensotec/ philips sensotec] [http://kinunia.cn/palma-di.htm palma di montechiaro] [http://bloprofeldi.info/lib/dinitro.htm dinitro-] [http://davte.info/library/html/giochi-online.htm giochi online azione] [http://kinunia.cn/galitsin.htm galitsin] [http://chaba.info/bandiera-inglese/ bandiera inglese] [http://helmed.info/topic/toshiba-mx/ toshiba m40x - 269] [http://bloprofeldi.info/lib/canon-efs.htm canon ef-s 55mm] [http://davte.info/library/html/dvd-verbatim.htm dvd verbatim azo] [http://nobinters.org/dono-damore.htm dono damore] [http://amohseni.info/img/styles/puglia-case/ puglia case vacanza] [http://bloprofeldi.info/lib/moda-pelle.htm moda pelle] [http://kinunia.cn/frigor-ariston.htm frigor ariston] [http://saibso.org/new-beetle.htm new beetle noleggio] [http://psisemiya.com/images/small/la-vita/ la vita provvisoria] [http://chaba.info/piu-che/ piu che puoi] [http://kinunia.cn/luomo-del.htm luomo del treno] [http://ashythro.info/library/html/videocamera-/ videocamera 3 ccd] [http://amohseni.info/img/styles/light-blue/ light blue dolce e gabbana] [http://helmed.info/topic/si-e/ si e llave tu] [http://helmed.info/topic/solo-sesso/ solo sesso gratis] [http://kinunia.cn/sophia-bush.htm sophia bush] [http://nobinters.org/legatoria-pc.htm legatoria pc] [http://bloprofeldi.info/lib/sit.htm sit] [http://psisemiya.com/images/small/alps-chieti/ alps chieti] [http://chaba.info/momentus/ momentus 7200] [http://davte.info/library/html/asus-my.htm asus my- pal a620] [http://chaba.info/old-mom/ old mom] [http://chaba.info/kenya-mombasa/ kenya mombasa voli] [http://amohseni.info/img/styles/oralb-professional/ oral-b professional care] [http://chaba.info/hp-fotocamere/ hp fotocamere digitali] [http://amohseni.info/img/styles/acer-travelmate/ acer travelmate 360] [http://chaba.info/azienda-agraria/ azienda agraria] [http://davte.info/library/html/piedi-con.htm piedi con calze video] [http://helmed.info/topic/benasi-satisfaction/ benasi satisfaction] [http://saibso.org/muvo-tx.htm muvo tx fm da 512 mb] [http://helmed.info/topic/hotel-costa/ hotel costa azzurra] [http://helmed.info/topic/you-spin/ you spin me right round baby] [http://chaba.info/dc-enhancer/ dc enhancer] {{Template:split-review}}
{{task}}

In this task, the goal is to find the <em>byte</em> length of a string. This means encodings like [[UTF-8]] may need to be handled specially, as there is not necessarily a one-to-one relationship between bytes and characters, and some languages recognize this.

For character length, see [[String Character Length]].

==[[4D]]==
[[Category:4D]]

$length:=Length("Hello, world!")

==[[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;
}

==[[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!";
std::string::size_type length = s.length(); // option 1: In Characters/Bytes
std::string::size_type size = s.size(); // option 2: In Characters/Bytes
// In bytes same as above since sizeof(char) == 1
std::string::size_type bytes = s.length() * sizeof(std::string::value_type);
}

For wide character strings:

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

==[[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!")

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

'''Interpreter:''' ANS Forth
CREATE s ," Hello world" \ create string "s"
s C@ ( -- length )

==[[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 length method of String objects returns the number of 16-bit values used to encode a string, so the number of bytes can be determined by doubling that number.

String s = "Hello, world!";
int byteCount = s.length() * 2;

An other way to know the byte length of a string is to explicitly specify the charset we desire.

String s = "Hello, world!";
int byteCountUTF16 = s.getByte("UTF-16").length;
int byteCountUTF8 = s.getByte("UTF-8").length;

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

JavaScript encodes strings in UTF-16, which represents each character with one or two 16-bit values. The length property of string objects gives the number of 16-bit values used to encode a string, so the number of bytes can be determined by doubling that number.

var s = "Hello, world!";
var byteCount = s.length * 2; //26

==[[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]] 5.8

Strings in Perl consist of characters. Measuring the byte length therefore requires conversion to some binary representation (called encoding, both noun and verb).

use utf8; # so we can use literal characters like ☺ in source
use Encode qw(encode);
print length encode 'UTF-8', "Hello, world! ☺";
# 17. The last character takes 3 bytes, the others 1 byte each.
print length encode 'UTF-16', "Hello, world! ☺";
# 32. 2 bytes for the BOM, then 15 byte pairs for each character.

==[[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;

==[[Pop11]]==
[[Category:Pop11]]

Currently Pop11 supports only strings consisting of 1-byte units.
Strings can carry arbitrary binary data, so user can for example
use UTF-8 (however builtin procedures will treat each byte as
a single character). The length function for strings returns
length in bytes:

lvars str = 'Hello, world!';
lvars len = length(str);

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

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

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

==[[Ruby]]==
[[Category:Ruby]]

string="Hello world"
print string.length
or
puts "Hello World".length

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

(string-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 bytelength "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 bytes is %d" $s1 [string bytelength $s1]]
puts [format "length of \"%s\" in bytes is %d" $s2 [string bytelength $s2]]

==[[Toka]]==
[[Category:Toka]]

This will include the terminating 0 in the length.

" hello, world!" count

==[[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]]
LenB(string|varname)

Returns the number of bytes required to store a string in memory
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:32, 19 January 2008

Redirect to: