Empty string: Difference between revisions
→{{header|Julia}}: A new entry for Julia |
Added an Algol 68 sample |
||
Line 44: | Line 44: | ||
.... |
.... |
||
}</lang> |
}</lang> |
||
=={{header|ALGOL 68}}== |
|||
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}} |
|||
<lang algol68># declare a string variable and assign an empty string to it # |
|||
STRING s := ""; |
|||
# test the string is empty # |
|||
IF s = "" THEN write( ( "s is empty", newline ) ) FI; |
|||
# test the string is not empty # |
|||
IF s /= "" THEN write( ( "s is not empty", newline ) ) FI; |
|||
# as a string is an array of characters, we could also test for emptyness by # |
|||
# checking for lower bound > upper bound # |
|||
IF LWB s > UPB s THEN write( ( "s is still empty", newline ) ) FI</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
Revision as of 12:39, 4 May 2015
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.
ACL2
To check if a string is empty: <lang Lisp>(= (length str) 0)</lang>
Ada
<lang Ada>procedure Empty_String is
function Is_Empty(S: String) return Boolean is begin return S = ""; -- test that S is empty end Is_Empty;
Empty: String := ""; -- Assign empty string XXXXX: String := "Not Empty";
begin
if (not Is_Empty(Empty)) or Is_Empty(XXXXX) then raise Program_Error with "something went wrong very very badly!!!"; end if;
end Empty_String;</lang>
Aime
<lang aime>text s; s = ""; if (length(s) == 0) {
...
} if (length(s) != 0) {
....
}</lang>
ALGOL 68
<lang algol68># declare a string variable and assign an empty string to it # STRING s := "";
- test the string is empty #
IF s = "" THEN write( ( "s is empty", newline ) ) FI;
- test the string is not empty #
IF s /= "" THEN write( ( "s is not empty", newline ) ) FI;
- as a string is an array of characters, we could also test for emptyness by #
- checking for lower bound > upper bound #
IF LWB s > UPB s THEN write( ( "s is still empty", newline ) ) FI</lang>
AutoHotkey
AutoHotkey has both "Traditional" or literal text, and "Expression" mode. This code demonstrates the task using both methods. <lang AutoHotkey>;; Traditional
- Assign an empty string
var =
- Check that a string is empty
If var =
MsgBox the var is empty
- Check that a string is not empty
If var !=
Msgbox the var is not empty
- Expression mode
- Assign an empty string
var := ""
- Check that a string is empty
If (var = "")
MsgBox the var is empty
- Check that a string is not empty
If (var != "")
Msgbox the var is not empty</lang>
AWK
<lang awk>#!/usr/bin/awk -f BEGIN {
# Demonstrate how to assign an empty string to a variable. a=""; b="XYZ"; print "a = ",a; print "b = ",b; print "length(a)=",length(a); print "length(b)=",length(b); # Demonstrate how to check that a string is empty. print "Is a empty ?",length(a)==0; print "Is a not empty ?",length(a)!=0; # Demonstrate how to check that a string is not empty. print "Is b empty ?",length(b)==0; print "Is b not empty ?",length(b)!=0;
}</lang>
- Output:
$ awk -f R/tmp/string.awk a = b = XYZ length(a)= 0 length(b)= 3 Is a empty ? 1 Is a not empty ? 0 Is b empty ? 0 Is b not empty ? 1
BASIC
<lang basic>10 LET A$="" 20 IF A$="" THEN PRINT "THE STRING IS EMPTY" 30 IF A$<>"" THEN PRINT "THE STRING IS NOT EMPTY" 40 END</lang>
Batch File
<lang dos> @echo off
- set "var" as a blank string.
set var=
- check if "var" is a blank string.
if not defined var echo Var is a blank string.
- Alternatively,
if %var%@ equ @ echo Var is a blank string.
- check if "var" is not a blank string.
if defined var echo Var is defined.
- Alternatively,
if %var%@ neq @ echo Var is not a blank string. </lang>
BBC BASIC
<lang bbcbasic> REM assign an empty string to a variable:
var$ = "" REM Check that a string is empty: IF var$ = "" THEN PRINT "String is empty" REM Check that a string is not empty: IF var$ <> "" THEN PRINT "String is not empty"
</lang>
Bracmat
There are two ways to assign a string to a variable. The variant using the =
operator does not evaluate the value before the assignment, the variant using the :
(match) operator does. If the value is a string, there is no difference, as a string always evaluates to itself.
<lang bracmat>( :?a
& (b=)
& abra:?c
& (d=cadabra)
& !a: { a is empty string }
& !b: { b is also empty string }
& !c:~ { c is not an empty string }
& !d:~ { neither is d an empty string }
)
</lang>
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 */
const 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>
Clojure
<lang clojure> (def x "") ;x is "globally" declared to be the empty string (let [x ""]
;x is bound to the empty string within the let )
(= x "") ;true if x is the empty string (not= x "") ;true if x is not the empty string </lang>
COBOL
<lang cobol>
IDENTIFICATION DIVISION. PROGRAM-ID. EMPTYSTR.
DATA DIVISION. WORKING-STORAGE SECTION. 01 str PIC X(10).
PROCEDURE DIVISION. Begin.
- * Assign an empty string.
INITIALIZE str.
- * Or
MOVE " " TO str.
IF (str = " ") DISPLAY "String is empty" ELSE DISPLAY "String is not empty" END-IF.
STOP RUN.
</lang>
CoffeeScript
Empty strings are mostly straightforward in CoffeeScript, but there's one gotcha.
<lang coffeescript> isEmptyString = (s) ->
# Returns true iff s is an empty string. # (This returns false for non-strings as well.) return true if s instanceof String and s.length == 0 s ==
empties = ["", , new String()] non_empties = [new String('yo'), 'foo', {}] console.log (isEmptyString(v) for v in empties) # [true, true, true] console.log (isEmptyString(v) for v in non_empties) # [false, false, false] console.log (s = ) == "" # true console.log new String() == # false, due to underlying JavaScript's distinction between objects and primitives </lang>
Common Lisp
Common Lisp treats empty strings as true (T in Common Lisp), therefore one must check the length of the string to know if it is empty or not. <lang lisp> (defparameter *s* "") ;; Binds dynamic variable *S* to the empty string "" (let ((s "")) ;; Binds the lexical variable S to the empty string ""
(= (length s) 0) ;; Check if the string is empty (> (length s) 0)) ;; Check if length of string is over 0 (that is: non-empty)
</lang>
Component Pascal
BlackBox Component Builder <lang oberon2> MODULE EmptyString; IMPORT StdLog;
PROCEDURE Do*;
VAR
s: ARRAY 64 OF CHAR;
(* s := "" <=> s[0] := 0X => s isEmpty*)
BEGIN
s := "";
StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = "");StdLog.Ln;
StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # "");StdLog.Ln;
StdLog.Ln;
(* Or *)
s := 0X;
StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = 0X);StdLog.Ln;
StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # 0X);StdLog.Ln;
StdLog.Ln;
END Do;
END EmptyString.
</lang>
Execute: ^Q EmptyString.Do
- Output:
Is 's' empty?:> $TRUE Is not 's' empty?:> $FALSE Is 's' empty?:> $TRUE Is not 's' empty?:> $FALSE
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 emptiness. <lang d>import std.array;
bool isEmptyNotNull(in string s) pure nothrow @safe {
return s is "";
}
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'); // D string literals are \0 terminated assert(s1.empty); assert(s2.isEmptyNotNull());
}</lang>
Dart
<lang dart>main() {
var empty = ;
if (empty.isEmpty) { print('it is empty'); }
if (empty.isNotEmpty) { print('it is not empty'); }
}</lang>
Déjà Vu
Like in Python, empty strings are falsy, non-empty strings are truthy. <lang dejavu>local :e ""
if not e:
!print "an empty string"
if e:
!print "not an empty string"</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>
DWScript
<lang delphi>var s : String;
s := ; // assign an empty string (can also use "")
if s = then
PrintLn('empty');
s := 'hello';
if s <> then
PrintLn('not empty');</lang>
Elixir
To check whether a given variable holds an empty string, either compare it to the empty string literal or check its length. <lang elixir> empty_string = "" not_empty_string = "a"
empty_string == ""
- => true
String.length(empty_string) == 0
- => true
not_empty_string == ""
- => false
String.length(not_empty_string) == 0
- => false
</lang>
Emacs Lisp
<lang Lisp>(setq str "") ;; empty string literal
(if (= 0 (length str))
(message "string is empty"))
(if (/= 0 (length str))
(message "string is not empty"))</lang>
Also possible is (string= "" str)
.
Erlang
<lang erlang> 1> S = "". % erlang strings are actually lists, so the empty string is the same as the empty list []. [] 2> length(S). 0 3> case S of [] -> empty; [H|T] -> not_empty end. empty 4> case "aoeu" of [] -> empty; [H|T] -> not_empty end. not_empty </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>
F#
<lang fsharp>open System
[<EntryPoint>] let main args =
let emptyString = String.Empty // or any of the literals "" @"" """""" printfn "Is empty %A: %A" emptyString (emptyString = String.Empty) printfn "Is not empty %A: %A" emptyString (emptyString <> String.Empty) 0</lang>
- Output:
Is empty "": true Is not empty "": false
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> \ string words operate on the address and count left on the stack by a string \ ? means the word returns a true/false flag on the stack
- empty? ( c-addr u -- ? ) nip 0= ;
- filled? ( c-addr u -- ? ) empty? 0= ;
- ="" ( c-addr u -- ) drop 0 ; \ It's OK to copy syntax from other languages
</lang>
Forth Console Test (True= -1, False=0)
s" This is not empty" empty? . 0 ok s" This is filled" filled? . -1 ok s" " empty? . -1 ok s" this is filled" ="" empty? . -1
Go
Go has no special syntax for empty strings. In Go variables are always initialized to a provided value or to the "zero value" of the type. The zero value of a string is the empty string. <lang go>// define and initialize an empty string var s string s2 := ""
// assign an empty string to a variable s = ""
// check that a string is empty, any of: s == "" len(s) == 0
// check that a string is not empty, any of: s != "" len(s) != 0 // or > 0</lang>
Groovy
<lang groovy>def s = // or "" if you wish assert s.empty
s = '1 is the loneliest number' assert !s.empty</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>
JavaScript
Create an empty String <lang javascript>var s = ""; var s = new String();</lang>
Boolean expressions representing emptiness <lang javascript>s == "" s.length == 0 !s !Boolean(s)</lang>
Non-emptiness <lang javascript>s != "" s.length != 0 s.length > 0 Boolean(s)</lang>
jq
jq strings are JSON strings. The empty string literal is simply "". It can be assigned to a variable as illustrated by this example:<lang jq>"" as $x </lang>If s is a string or an array, then the additive "zero" for s can be created by writing s[0:0]. That is, if s is a string, then s[0:0] will yield the empty string. This is useful when writing polymorphic functions.
To determine whether a string, s, is empty:<lang jq>s == ""
- or:
s|length == 0</lang>To determine whether a string, s, is non-empty:<lang jq>s != ""
- or:
s.length != 0 # etc.</lang>
Julia
<lang Julia> blank = "" nonblank = "!"
println("The length of blank is ", length(blank)) println("That blank is empty is ", isempty(blank)) println("That blank is not empty is ", !isempty(blank))
println() println("The length of nonblank is ", length(nonblank)) println("That nonblank is empty is ", isempty(nonblank)) println("That nonblank is not empty is ", !isempty(nonblank)) </lang>
- Output:
The length of blank is 0 That blank is empty is true That blank is not empty is false The length of nonblank is 1 That nonblank is empty is false That nonblank is not empty is true
K
<lang K> variable: ""
0=#variable
1
0<#variable
0</lang>
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lasso
<lang Lasso>//Demonstrate how to assign an empty string to a variable. local(str = string) local(str = )
//Demonstrate how to check that a string is empty.
- str->size == 0 // true
not #str->size // true
//Demonstrate how to check that a string is not empty. local(str = 'Hello, World!')
- str->size > 0 // true
- str->size // true</lang>
LFE
<lang lisp> > (set str "") () > (length str) 0 > (=:= 0 (length str)) true > (=:= 0 (length "apple")) false > (=:= "apple" "") false > (=/= "apple" "") true > (=:= str "") true > (=:= "apple" '()) false > (=/= "apple" '()) true > (=:= str '()) true > (case str ('() 'empty) ((cons head tail) 'not-empty)) empty > (case "apple" ('() 'empty) ((cons head tail) 'not-empty)) not-empty </lang>
Lhogho
Lhogho is a Logo compiler for Windows and Linux <lang logo>make "str " ;make null-string word print empty? :str ;prints 'true' print not empty? :str ;prints 'false' </lang>
Liberty BASIC
<lang lb> 'assign empty string to variable a$ = "" 'check for empty string if a$="" then print "Empty string." if len(a$)=0 then print "Empty string." 'check for non-empty string if a$<>"" then print "Not empty." if len(a$)>0 then print "Not empty." </lang>
LOLCODE
The empty string is a false value in LOLCODE, and is thus amenable to use as the condition of an O RLY? <lang LOLCODE>HAI 1.3
I HAS A string ITZ "" string, O RLY?
YA RLY, VISIBLE "STRING HAZ CONTENZ" NO WAI, VISIBLE "Y U NO HAS CHARZ?!"
OIC
KTHXBYE</lang>
Lua
<lang Lua>str = "" -- create empty string
-- test for empty string if str == "" then
print "The string is empty"
end
-- test for nonempty string if str ~= "" then
print "The string is not empty"
end</lang>
Maple
<lang Maple> s := ""; # Create an empty string evalb(s = ""); # test if the string is empty evalb(s <> ""); # test if the string is not empty </lang>
Mathematica
<lang Mathematica> str=""; (*Create*) str==="" (*test empty*) str=!="" (*test not empty*) </lang>
MATLAB / Octave
<lang Matlab> % Demonstrate how to assign an empty string to a variable.
str = ; % Demonstrate how to check that a string is empty. isempty(str) (length(str)==0) % Demonstrate how to check that a string is not empty. ~isempty(str) (length(str)>0)</lang>
Maxima
<lang maxima>s: ""$
/* check using string contents */ sequal(s, ""); not sequal(s, "");
/* check using string length */ slength(s) = ""; slength(s) # "";</lang>
Mirah
<lang mirah>empty_string1 = "" empty_string2 = String.new
puts "empty string is empty" if empty_string1.isEmpty() puts "empty string has no length" if empty_string2.length() == 0 puts "empty string is not nil" unless empty_string1 == nil</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>
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary
s1 = -- assignment s2 = "" -- equivalent to s1 parse '.' . s3 . -- parsing a token that doesn't exist results in an empty string
strings = [s1, s2, s3, ' ']
loop s_ = 0 to strings.length - 1
say (Rexx s_).right(3)':\-' select when strings[s_] == then say ' "'strings[s_]'" is really empty' when strings[s_].length = 0 then say ' "'strings[s_]'" is empty' when strings[s_] = then say ' "'strings[s_]'" looks empty but may not be' when strings[s_].length > 0 then say ' "'strings[s_]'" is not empty' otherwise nop end end s_
return </lang>
- Output:
0: "" is really empty 1: "" is really empty 2: "" is really empty 3: " " looks empty but may not be
Nim
<lang nim>var x = ""
if x == "":
echo "empty"
if x != "":
echo "not empty"
- Alternatively:
if x.len == 0:
echo "empty"
if x.len > 0:
echo "not empty"</lang>
Objeck
<lang objeck> s := ""; if(s->IsEmpty()) {
"s is empty"->PrintLine();
} else{
"s is not empty"->PrintLine();
}; </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>
- Output:
s1 empty? true s2 empty? false
Oforth
isEmpty can be used on all collections, not only strings.
<lang Oforth>"" isEmpty "" isEmpty not</lang>
OpenEdge/Progress
Strings can be stored in CHARACTER and LONGCHAR variables. Both are initially empty. Both can also be unknown. A CHARACTER has a maximum length of approx 32000 bytes.
<lang progress>DEFINE VARIABLE cc AS CHARACTER.
IF cc > THEN
MESSAGE 'not empty' VIEW-AS ALERT-BOX.
ELSE IF cc = ? THEN
MESSAGE 'unknown' VIEW-AS ALERT-BOX.
ELSE /* IF cc = */
MESSAGE 'empty' VIEW-AS ALERT-BOX.
</lang>
PARI/GP
<lang parigp>a=""; isEmpty(s)=s=="" \\ Alternately: isEmpty(s)=#s==0 isNonempty(s)=s!="" \\ Alternatively: isNonempty(s)=#s</lang>
Pascal
See Delphi
Perl
<lang perl>if ($s eq "") { # Test for empty string
print "The string is empty";
} if ($s ne "") { # Test for non empty string
print "The string is not empty";
}</lang>
In Perl, an empty string is often used to represent a false value. <lang Perl>$s = ""; if ($s) { ... } # false
- 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 ""
- 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
- 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>
PHP
<lang Php><?php
$str = ; // assign an empty string to a variable
// check that a string is empty if (empty($str)) { ... }
// check that a string is not empty if (! empty($str)) { ... }
// we could also use the following if ($str == ) { ... } if ($str != ) { ... }
if (strlen($str) == 0) { ... } if (strlen($str) != 0) { ... }</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)
- To check for an empty string:
(or String ..) (ifn String ..) (unless String ..)
- or a non-empty string:
(and String ..) (if String ..) (when String ..)</lang>
PL/I
<lang PL/I>Dcl s Char(10) Varying; s = ; /* assign an empty string to a variable. */ if length(s) = 0 then ... /* To test whether a string is empty */ if length(s) > 0 then ... /* to test for a non-empty string */ </lang>
Prolog
<lang prolog>assign_empty_string(Variable) :- Variable = "".
is_empty_string(String) :- String == "". not_empty_string(String) :- 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>
- 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>
R
<lang R>s <-
if (s == ) cat('Empty\n')
- or
if (nchar(s) == 0) cat('Empty\n')
if (s != ) cat('Not empty\n')
- or
if (nchar(s) > 0) cat('Not empty\n')</lang>
Racket
<lang Racket>#lang racket
(define empty-string "") (define (string-null? s) (string=? "" s)) (define (string-not-null? s) (string<? "" s))</lang>
Rascal
<lang rascal>str s = ""; if (s=="") print("string s is empty"); if (s!="") print("string s is not empty"); </lang> Or the build-in operator: <lang rascal>import String; if (isEmpty(s)) print("string s is empty"); if (isEmpty(s)) print("string s is not empty");</lang>
Retro
Create an empty string and assign it to a variable. In these keepString is used to ensure that the string is permanent.
<lang Retro> ( by creating a variable ) "" keepString variable: foo
( by setting an existing variable 'foo' ) "" keepString !foo </lang>
Checking that a string is empty. A string with a length of zero is assumed to be empty.
<lang Retro>
- emtpy? ( $-f ) getLength 0 = ;
"" empty? putn "hello" empty? putn </lang>
Check that a string is not empty.
<lang Retro>
- notEmpty? ( $-f ) getLength 0 > ;
"" notEmpty? putn "hello" notEmpty? putn </lang>
REXX
<lang rexx>/*REXX: how to assign an empty string & then check for empty/not-empty.*/
/*─────────────── 3 simple wats to assign an empty string to a variable.*/ auk= /*uses two single quotes or apostrophies. */ ide="" /*uses two quotes, sometimes called a double quote.*/ doe= /*... nothing at all. */
/*─────────────── assigning multiple null values to vars, 2 methods are:*/ ram=0 parse var ram . emu pug yak nit moa owl pas jay koi ern ewe fae gar hob
/*where the value of zero is skipped, the rest set to null,*/ /*which is the next value AFTER the value of RAM (nothing).*/
/*───or─── (with less clutter ─── or more, ... perception).*/
parse value 0 with . ant ape ant imp fly tui paa elo dab cub bat ayu
/*where the value of zero is skipped, the rest set to null,*/ /*which is the next value AFTER the 0 (zero): nothing. */
/*─────────────── how to check that a string is empty, several methods: */ if cat== then say "the feline is not here." if pig=="" then say 'no ham today' if length(gnu)==0 then say "the wildebeast is empty & hungry." if length(ips)=0 then say "checking with == instead of = is faster" if length(hub)<1 then method = "obtuse, don't do as I do ..."
nit= /*assign an empty string to a lice egg.*/ if cow==nit then say 'the cow has no milk today.'
/*─────────────── how to check that a string isn't empty, several ways: */ if dog\== then say "the dogs are out!"
/*most REXXes support the "not" character. */
if fox¬== then say "and the fox is in the henhouse." if length(rat)>0 then say "the rat is singing" /*ugly way to test.*/
if elk== then nop; else say "long way for an elk to be tested."
if length(eel)\==0 then fish=eel /*fast compare, quick.*/ if length(cod)\=0 then fish=cod /*not-so-fast compare.*/
/*────────────────────────── anyway, as they say: "choose your poison." */</lang>
Ruby
Create an empty string <lang ruby>s = "" s = String.new s = "any string"; s.clear</lang>
These expressions all evaluate to true to determine emptiness: <lang ruby>s == "" s.eql?("") s.empty? s.length == 0 s[/\A\z/]
- also silly things like
s.each_char.to_a.empty?</lang>
Non-empty expressions, in addition to simply negating the above expressions: <lang ruby>s != "" s.length > 0 s[/./m]</lang>
Note that we can not do the following, because the empty string is equivalent to true in Ruby (Boolean values#Ruby): <lang ruby>if s then puts "not empty" end # This code is wrong!</lang>
Run BASIC
<lang runbasic>var$ = "" ' -------------- 'empty string ' ------------- if var$="" then print "String is Empty" if len(var$)=0 then print "String is Empty" ' ------------- 'not empty string ' ------------- if var$<>"" then print "String Not empty." if len(var$)>0 then print "String Not empty."</lang>
Scala
<lang scala>// assign empty string to a variable val s="" // check that string is empty s.isEmpty // true s=="" // true s.size==0 // true // check that string is not empty s.nonEmpty // false s!="" // false s.size>0 // false</lang>
Scheme
<lang scheme>(define empty-string "") (define (string-null? s) (string=? "" s)) (define (string-not-null? s) (string<? "" s))</lang>
Seed7
<lang seed7># assign empty string to a variable s := ""
- check that string is empty
s = ""
- check that string is not empty
s <> ""</lang>
Sidef
Create an empty string: <lang ruby>s = ""; s = String.new;</lang>
These expressions all evaluate to true to determine emptiness: <lang ruby>s == ""; s.length == 0; s.is_empty; s ~~ /^\z/; /\A\z/.match(s)??;</lang>
Non-empty expressions, in addition to simply negating the above expressions: <lang ruby>s != ""; s.length?; s.length > 0; s ~~ /./s; s !~ /^\z/; /./s.match(s)??;</lang>
Smalltalk
<lang smalltalk> "Assign empty string to a variable" str := .
"Check that string is empty" str isEmpty.
"Check that string is not empty" str isEmpty not. </lang>
Standard ML
<lang sml>(* Assign empty string to a variable *) val s = "" (* Check that a string is empty*) s = "" (* Check that a string is nonempty *) s <> ""</lang>
Swift
<lang swift>var s = "" if s.isEmpty { // alternately, s == ""
println("s is empty")
} else {
println("s is not empty")
}</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>
TorqueScript
Assign an empty string to $empty
$empty = "";
Check if $empty is an empty string
if($empty $= "") { echo("$empty is an empty string."); }
Check if $empty is not an empty string
if($empty !$= "") { echo("$empty is not an empty string."); }
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT s="" IF (s=="") PRINT "s is an empty string" IF (s!="") PRINT "s is a non-empty string" </lang>
- Output:
s is an empty string
TXR
Pattern Matching
<lang txr>@(bind a "")</lang>
If a
is unbound, a binding is created, containing the empty string.
If a
is already bound, bind
succeeds if a
contains the empty string, and the pattern matching continues at the next directive.
Or else a failure occurs, triggering backtracking behavior.
TXR Lisp
<lang lisp>@(do (defvar *a* "")
(if (equal *a* "") (format t "empty string\n")) (set *a* "nonempty") (if (zerop (length *a*)) (format t "guess what?\n")))</lang>
UNIX Shell
<lang bash># assign an empty string to a variable s=""
- the "test" command can determine truth by examining the string itself
if [ "$s" ]; then echo "not empty"; else echo "empty"; fi
- 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
- 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.
VBA
<lang vb> dim s as string
' assign an empty string to a variable: s = ""
' test if a string is empty: if s = "" then Debug.Print "empty!" ' or: if Len(s) = 0 then Debug.Print "still empty!"
'test if a string is not empty: if s <> "" then Debug.Print "not an empty string" 'or: if Len(s) > 0 then Debug.Print "not empty." </lang>
XPL0
<lang XPL0>code Text=12; string 0; \use zero-terminated convention, instead of MSb set char S; [S:= ""; \assign an empty string if S(0) = 0 then Text(0, "empty "); S:= "Hello"; if S(0) # 0 then Text(0, "not empty "); ]</lang>
zkl
<lang zkl>s:=""; s.toBool() //-->False if (s) println("not empty")</lang>
- Programming Tasks
- Solutions by Programming Task
- String manipulation
- Simple
- ACL2
- Ada
- Aime
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- Batch File
- BBC BASIC
- Bracmat
- C
- C++
- C sharp
- Clojure
- COBOL
- CoffeeScript
- Common Lisp
- Component Pascal
- D
- Dart
- Déjà Vu
- Delphi
- DWScript
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Fantom
- Forth
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- K
- LabVIEW
- Lasso
- LFE
- Lhogho
- Liberty BASIC
- LOLCODE
- Lua
- Maple
- Mathematica
- MATLAB
- Octave
- Maxima
- Mirah
- Nemerle
- NetRexx
- Nim
- Objeck
- OCaml
- Oforth
- OpenEdge/Progress
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Prolog
- PureBasic
- Python
- R
- Racket
- Rascal
- Retro
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Sidef
- Smalltalk
- Standard ML
- Swift
- Tcl
- TorqueScript
- TUSCRIPT
- TXR
- UNIX Shell
- VBA
- XPL0
- Zkl
- GUISS/Omit