Empty string

From Rosetta Code
Task
Empty string
You are encouraged to solve this task according to the task description, using any language you may know.

Languages may have features for dealing specifically with empty strings (those containing no characters).

The task is to:

  • Demonstrate how to assign an empty string to a variable.
  • Demonstrate how to check that a string is empty.
  • Demonstrate how to check that a string is not empty.

C

In C the strings are char pointers. A string terminates with the null char (U+0000, '\0'), which is not considered part of the string. Thus an empty string is "\0", while a null string is a null pointer which points to nothing. <lang C>/* assign an empty string */ char *str = ""; /* to test a null string */ if (str) { ... } /* to test if string is empty */ if (str[0] == '\0') { ... } /* or equivalently use strlen function */ if (strlen(str) == 0) { ... } /* or compare to a known empty string, same thing. "== 0" means strings are equal */ if (strcmp(str, "") == 0) { ... } </lang>

C++

<lang cpp>#include <string>

// ...

std::string str; // a string object for an empty string

if (str.empty()) { ... } // to test if string is empty

// we could also use the following if (str.length() == 0) { ... } if (str == "") { ... }</lang>

C#

<lang csharp>using System;

class Program {

   static void Main (string[] args) {
       string example = string.Empty;
       if (string.IsNullOrEmpty(example)) { }
       if (!string.IsNullOrEmpty(example)) { }
   }

} </lang>

D

D treats null strings and empty strings as equal on the value level, but different on object level. You need to take this into account when checking for empty. <lang d>void main(){

   string s1 = null;
   string s2 = "";
   
   // the content is the same
   assert(!s1.length); 
   assert(!s2.length);
   assert(s1 == "" && s1 == null); 
   assert(s2 == "" && s2 == null);
   assert(s1 == s2);
   // but they don't point to the same memory region
   assert(s1 is null && s1 !is "");
   assert(s2 is "" && s2 !is null);
   assert(s1 !is s2);
   assert(s1.ptr == null);
   assert(*s2.ptr == '\0');
   
   assert(isEmpty(s1));    
   assert(isEmptyNotNull(s2));    

}

bool isEmpty(string s) {

   return !s.length;

}

bool isEmptyNotNull(string s) {

   return s is "";

}</lang>

Delphi

<lang Delphi>program EmptyString;

{$APPTYPE CONSOLE}

uses SysUtils;

function StringIsEmpty(const aString: string): Boolean; begin

 Result := aString = ;

end;

var

 s: string;

begin

 s := ;
 Writeln(StringIsEmpty(s)); // True
 s := 'abc';
 Writeln(StringIsEmpty(s)); // False

end.</lang>

Euphoria

<lang euphoria>sequence s

-- assign an empty string s = ""

-- another way to assign an empty string s = {} -- "" and {} are equivalent

if not length(s) then

   -- string is empty

end if

if length(s) then

   -- string is not empty

end if</lang>

Fantom

Fantom uses "" to represent an empty string, and provides the isEmpty method to check if a string is empty.

<lang fantom> a := "" // assign an empty string to 'a' a.isEmpty // method on sys::Str to check if string is empty a.size == 0 // what isEmpty actually checks a == "" // alternate check for an empty string !a.isEmpty // check that a string is not empty </lang>

Forth

Strings are represented as an addr-len pair on the stack. An empty string has len 0.

<lang forth>: empty? ( str len -- ? ) nip 0= ;

s" " dup . empty? . \ 0 -1</forth>

Go

Go has no special syntax for empty strings <lang go>// assign empty string to a variable s = ""

// check that string is empty s == ""

// check that string is not empty s > ""</lang>

Haskell

<lang haskell>import Control.Monad

-- In Haskell strings are just lists (of characters), so we can use the function -- 'null', which applies to all lists. We don't want to use the length, since -- Haskell allows infinite lists.

main = do

 let s = ""
 when (null s) (putStrLn "Empty.")
 when (not $ null s) (putStrLn "Not empty.")</lang>

Icon and Unicon

Icon and Unicon can produce empty strings in several ways: <lang Icon>s := "" # null string s := string('A'--'A') # ... converted from cset difference s := char(0)[0:0] # ... by slicing

s1 == "" # lexical comparison, could convert s1 to string s1 === "" # comparison won't force conversion

  • s1 = 0 # zero length, however, *x is polymorphic
  • string(s1) = 0 # zero length string

s1 ~== "" # non null strings comparisons s1 ~=== ""

  • string(s1) ~= 0

s := &null # NOT a null string, null type /s # test for null type \s # test for non-null type </lang>

J

<lang j> variable=:

  0=#variable

1

  0<#variable

0</lang>

Note that J attempts to make no distinction between empty lists, regardless of their type. In other words, while some operations can reveal the type of an empty list (for example, anything that can introduce padding based on the type of the list itself) this distinction is ignored whenever possible. You can perform arithmetic on an empty string, and you can append text to an empty list of numbers even though these operations would not succeed on non-empty lists of the same type.

Thus it's not appropriate, in general case J code, to check that an empty string is of type string.

Note also that in an if. or while. statement, J treats an empty string (or the absence of any argument) as true.

Java

String.isEmpty() is part of Java 1.6. Other options for previous versions are noted. <lang java5>String s = ""; if(s != null && s.isEmpty()){//optionally, instead of "s.isEmpty()": "s.length() == 0" or "s.equals("")"

  System.out.println("s is empty");

}else{

  System.out.println("s is not empty");

}</lang>


Mathematica

<lang Mathematica> str=""; (*Create*) str==="" (*test empty*) str=!="" (*test not empty*) </lang>

Nemerle

Assign an empty string: <lang Nemerle>def empty = ""; mutable fill_later = "";</lang> Check if a string is empty/not empty: <lang Nemerle>a_string == ""; a_string != 0; a_string.Length == 0; a_string.Length > 0;</lang>

OCaml

<lang ocaml>let is_string_empty s =

 (s = "")

let () =

 let s1 = ""
 and s2 = "not empty" in
 Printf.printf "s1 empty? %b\n" (is_string_empty s1);
 Printf.printf "s2 empty? %b\n" (is_string_empty s2);
</lang>

outputs:

s1 empty? true
s2 empty? false

PARI/GP

<lang parigp>a=""; isEmpty(s)=s=="" \\ Alternately: isEmpty(s)=#s==0 isNonempty(s)=s!="" \\ Alternatively: isNonempty(s)=#s</lang>

Perl

In Perl, an empty string is often used to represent a false value. <lang Perl>$s = ""; if ($s) { ... } # false

  1. to tell if a string is false because it's empty, or it's plain not there (undefined)

$s = undef; if (defined $s) { ... } # false; would be true on ""

  1. though, perl implicitly converts between strings and numbers, so this is also false

$s = "0"; if ($s) { ... } # false; also false on "000", "0.0", "\x0", "0 with text", etc

  1. but a string that converts to number 0 is not always false, though:

$s = "0 but true"; if ($s) { ... } # it's true! black magic!</lang>

Perl 6

In Perl 6 we can't just test a string for truth to determine if it has a value. The string "0" will test as false even though it has a value. Instead we must test for length.

<lang perl6>my $s = ; say 'String is empty' unless $s.chars; say 'String is not empty' if $s.chars;</lang>

PicoLisp

The empty string is represented by 'NIL' in PicoLisp. During input, two subsequent double quotes '""' return the symbol NIL. <lang PicoLisp># To assign a variable an empty string: (off String) (setq String "") (setq String NIL)

  1. To check for an empty string:

(or String ..) (ifn String ..) (unless String ..)

  1. or a non-empty string:

(and String ..) (if String ..) (when String ..)</lang>

PureBasic

In PureBasic we can just test a string for truth to determine if it has a value. <lang PureBasic>Procedure.s isStringEmpty(a.s)

 If a
   ProcedureReturn "String is not empty, it contains '" + a + "'."
 Else
   ProcedureReturn "String is empty, or null."
 EndIf 

EndProcedure

If OpenConsole()

 Define a.s = ""
 Define b.s = "stuff"
 PrintN(isStringEmpty(a))
 PrintN(isStringEmpty(b))
 
 Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
 CloseConsole()

EndIf</lang> Sample output:

String is empty, or null.
String is not empty, it contains 'stuff'.

Python

The empty string is printed by Python REPL as '', and is treated as boolean false (as are most empty container types, by convention). Any non-empty string, including '0', is always treated as True in a boolean context. <lang python>s = if not s:

   print('String s is empty.')

if s:

   print('String s is not empty.')</lang>

Seed7

<lang seed7># assign empty string to a variable s := ""

  1. check that string is empty

s = ""

  1. check that string is not empty

s <> ""</lang>

Tcl

The only special position that the empty string has in Tcl is that a great many commands return it, and the REPL of tclsh and wish doesn't print it. Otherwise, it is just like any other value. <lang tcl>set s "" if {$s eq ""} {puts "s contains an empty string"} if {$s ne ""} {puts "s contains a non-empty string"}</lang> There are other ways to check for emptiness and non-emptiness too (though the above are favored for reasons of simplicity, clarity and speed): <lang tcl>if {[string equal $s ""]} {puts "is empty"} if {[string length $s] == 0} {puts "is empty"} if {[string compare $s ""] != 0} {puts "is non-empty"}</lang>

UNIX Shell

<lang bash># assign an empty string to a variable s=""

  1. the "test" command can determine truth by examining the string itself

if [ $s ]; then echo "not empty"; else echo "empty"; fi

  1. compare the string to the empty string

if [ "$s" = "" ]; then echo "s is the empty string"; fi if [ "$s" != "" ]; then echo "s is not empty"; fi

  1. examine the length of the string

if [ -z "$s" ]; then echo "the string has length zero: it is empty"; fi if [ -n "$s" ]; then echo "the string has length non-zero: it is not empty"; fi</lang>

When using comparison operators, it is crucial to double-quote the variable within the conditional expression. This will ensure the shell sees the correct number of arguments. For example, if one were to write [ $s = "" ], then after variable substitition, the shell will try to evaluate [ = "" ] which is a syntax error.