Empty string: Difference between revisions

64,555 bytes added ,  2 months ago
removed langur language example for now
(Added FutureBasic example)
(removed langur language example for now)
 
(169 intermediate revisions by 79 users not shown)
Line 1:
{{task}}
[[Category:String manipulation]] [[Category:Simple]]
 
Languages may have features for dealing specifically with empty strings
Line 9 ⟶ 10:
::*   Demonstrate how to check that a string is empty.
::*   Demonstrate how to check that a string is not empty.
 
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
[[Category:String manipulation]] [[Category:Simple]]
<syntaxhighlight lang="11l">V s = ‘’
I s.empty
print(‘String s is empty.’)
I !s.empty
print(‘String s is not empty.’)</syntaxhighlight>
 
=={{header|6502 Assembly}}==
An empty string is just a null terminator with no text in front.
<syntaxhighlight lang="6502">EmptyString:
byte 0</syntaxhighlight>
 
Checking if a string is empty is simple, just count the number of characters before you reach the terminator. If that count equals zero, the string is empty. Otherwise, the string is not empty.
 
<syntaxhighlight lang="6502asm">lda #<EmptyString ;address of string we wish to check
sta $00
lda #>EmptyString
sta $01 ;the empty string has been assigned to zero page pair $00 and $01
 
ldy #0
ldx #0
getStringLength:
lda ($00),y
beq Terminated
iny
jmp getStringLength
Terminated:
cpy #0
beq StringIsEmpty ;if this branch is taken, the string is empty
;otherwise, the string is not empty</syntaxhighlight>
 
=={{header|68000 Assembly}}==
{{trans|6502 Assembly}}
An empty string is just a null terminator with no text in front.
<syntaxhighlight lang="68000devpac">EmptyString:
DC.B 0
EVEN</syntaxhighlight>
Checking if a string is empty is simple, just count the number of characters before you reach the terminator. If that count equals zero, the string is empty. Otherwise, the string is not empty.
<syntaxhighlight lang="68000devpac">LEA EmptyString,A0 ;assign the empty string to address register A0
 
getStringLength:
MOVE.L A0,-(SP) ;push A0 onto the stack. This will be used to check if the string is empty.
 
loop_getStringLength:
MOVE.B (A0)+,D0
BEQ Terminated
JMP loop_getStringLength
 
SUBQ.L #1,A0 ;after the terminator is read, A0 is incremented to point to the byte after it. This fixes that.
CMP.L A0,(SP) ;compare the current A0 with the original value.
BEQ StringIsEmpty ;if they are equal, then nothing was read besides the terminator. Therefore the string is empty.
;if the above branch wasn't taken, the string is not empty and execution arrives here.</syntaxhighlight>
 
=={{header|8th}}==
Assign an empty string to a variable:
<langsyntaxhighlight Forthlang="forth">"" var, str</langsyntaxhighlight>
 
Check that the string is empty:
<langsyntaxhighlight Forthlang="forth">str @ s:len 0 n:= if ... then</langsyntaxhighlight>
 
The check for a non-empty string is the same, but with "not" after the n:=
 
=={{header|AArch64 Assembly}}==
 
Declare an empty string at address <code>str</code>:
 
<syntaxhighlight lang="arm_assembly">str: .asciz ""</syntaxhighlight>
 
Check if a string stored at <code>x0</code> is empty:
 
<syntaxhighlight lang="arm_assembly"> mov x5, #0
ldrb w5, [x0]
cmp x5, #0</syntaxhighlight>
 
Full program demo:
 
{{works with|aarch64-linux-gnu-as/qemu-aarch64}}
 
<syntaxhighlight lang="arm_assembly">.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
 
.text
.global _start
 
_start:
stp x29, x30, [sp, -16]!
ldr x0, =str1
mov x29, sp
bl str_empty // str_empty("");
ldr x0, =str2
bl str_empty // str_empty("non-empty");
ldp x29, x30, [sp], 16
mov x0, #0
b _exit
 
str1: .asciz ""
str2: .asciz "non-empty"
.align 4
 
// void str_empty(const char *s) - print "String is empty" if s is empty, "String is not empty" otherwise
str_empty:
mov x5, #0
ldrb w5, [x0]
ldr x1, =msg_empty
ldr x3, =msg_not_empty
mov x2, #16
mov x4, #20
cmp x5, #0
csel x1, x1, x3, eq // msg = s[0] == 0 ? msg_empty : msg_not_empty;
csel x2, x2, x4, eq // len = s[0] == 0 ? 16 : 20;
mov x0, #STDOUT
b _write // write(stdout, msg, len);
 
msg_empty:
.ascii "String is empty\n"
msg_not_empty:
.ascii "String is not empty\n"
.align 4
 
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
stp x29, x30, [sp, -16]!
mov x8, #SVC_WRITE
mov x29, sp
svc #0
ldp x29, x30, [sp], 16
ret
 
// void _exit(int retval)
_exit:
mov x8, #SVC_EXIT
svc #0</syntaxhighlight>
 
=={{header|ACL2}}==
To check if a string is empty:
<langsyntaxhighlight Lisplang="lisp">(= (length str) 0)</langsyntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC CheckIsEmpty(CHAR ARRAY s)
PrintF("'%S' is empty? ",s)
IF s(0)=0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC Main()
CHAR ARRAY str1,str2
 
str1=""
str2="text"
 
CheckIsEmpty(str1)
CheckIsEmpty(str2)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Empty_string.png Screenshot from Atari 8-bit computer]
<pre>
'' is empty? True
'text' is empty? False
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">procedure Empty_String is
 
function Is_Empty(S: String) return Boolean is
Line 41 ⟶ 196:
raise Program_Error with "something went wrong very very badly!!!";
end if;
end Empty_String;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">text s;
s = "";
if (length(s) == 0) {
Line 51 ⟶ 206:
if (length(s) != 0) {
....
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># declare a string variable and assign an empty string to it #
STRING s := "";
 
Line 66 ⟶ 221:
# 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</langsyntaxhighlight>
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>
String.isBlank(record.txt_Field__c);
--Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
</syntaxhighlight>
</lang>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝⍝ Assign empty string to A
A ← ''
0 = ⍴∊ A
1
~0 = ⍴∊ A
0
</syntaxhighlight>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
<lang AppleScript>
-- assign empty string to str
set str to ""
Line 106 ⟶ 271:
-- str is not empty
end if
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program strEmpty.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szNotEmptyString: .asciz "String is not empty. \n"
szEmptyString: .asciz "String is empty. \n"
@ empty string
szString: .asciz "" @ with zero final
szString1: .asciz "A" @ with zero final
 
/* UnInitialized data */
.bss
 
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
 
@ load string
ldr r1,iAdrszString
ldrb r0,[r1] @ load first byte of string
cmp r0,#0 @ compar with zero ?
bne 1f
ldr r0,iAdrszEmptyString
bl affichageMess
b 2f
1:
 
ldr r0,iAdrszNotEmptyString
bl affichageMess
/* second string */
2:
@ load string 1
ldr r1,iAdrszString1
ldrb r0,[r1] @ load first byte of string
cmp r0,#0 @ compar with zero ?
bne 3f
ldr r0,iAdrszEmptyString
bl affichageMess
b 100f
3:
ldr r0,iAdrszNotEmptyString
bl affichageMess
b 100f
 
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszString: .int szString
iAdrszString1: .int szString1
iAdrszNotEmptyString: .int szNotEmptyString
iAdrszEmptyString: .int szEmptyString
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">s: ""
 
if empty? s -> print "the string is empty"
if 0 = size s -> print "yes, the string is empty"
 
s: "hello world"
 
if not? empty? s -> print "the string is not empty"
if 0 < size s -> print "no, the string is not empty"</syntaxhighlight>
 
{{out}}
 
<pre>the string is empty
yes, the string is empty
the string is not empty
no, the string is not empty</pre>
 
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">string c; //implicitly assigned an empty string
if (length(c) == 0) {
write("Empty string");
} else {
write("Non empty string");
}
 
string s = ""; //explicitly assigned an empty string
if (s == "") {
write("Empty string");
}
if (s != "") {
write("Non empty string");
}
 
string t = "not empty";
if (t != "") {
write("Non empty string");
} else {
write("Empty string");
}</syntaxhighlight>
{{out}}
<pre>Empty string
Empty string
Non empty string</pre>
 
=={{header|AutoHotkey}}==
AutoHotkey has both "Traditional" or literal text, and "Expression" mode.
This code demonstrates the task using both methods.
<langsyntaxhighlight AutoHotkeylang="autohotkey">;; Traditional
; Assign an empty string:
var =
Line 130 ⟶ 431:
; Check that a string is not empty
If (var != "")
Msgbox the var is not empty</langsyntaxhighlight>
 
=={{header|Avail}}==
The type string is defined as <code><character…|></code> (a tuple of characters), so the empty tuple and the empty string are equivalent values, and all tuple/collection methods can be used on strings.
 
<syntaxhighlight lang="avail">emptyStringVar : string := "";
Assert: emptyStringVar = "";
Assert: emptyStringVar = <>;
Assert: emptyStringVar is empty;
Assert: |emptyStringVar| = 0;</syntaxhighlight>
 
Checking that a string is _not_ empty generally isn't any more interesting, just a logical negation of the above tests.
 
<syntaxhighlight lang="avail">nonemptyStringVar : string := "content!";
Assert: nonemptyStringVar ≠ "";
Assert: nonemptyStringVar ≠ <>;
Assert: ¬nonemptyStringVar is empty;
Assert: |nonemptyStringVar| > 0;</syntaxhighlight>
 
The library also defines a type _nonempty string_, which can be leveraged for a type-membership check.
 
<syntaxhighlight lang="avail">Assert: nonemptyStringVar ∈ nonempty string;</syntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
# Demonstrate how to assign an empty string to a variable.
Line 148 ⟶ 470:
print "Is b empty ?",length(b)==0;
print "Is b not empty ?",length(b)!=0;
}</langsyntaxhighlight>
{{out}}
<pre>$ awk -f R/tmp/string.awk
Line 162 ⟶ 484:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">""→Str1
!If length(Str1)
Disp "EMPTY",i
Else
Disp "NOT EMPTY",i
End</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
The terminating quote may be left off. By default, strings are initially empty so the assignment is not necessary. Another way to check for an empty string is to use the LEN function.
<langsyntaxhighlight lang="basic"> 10 LET A$ = "
40 IF LEN (A$) = 0 THEN PRINT "THE STRING IS EMPTY"
50 IF LEN (A$) THEN PRINT "THE STRING IS NOT EMPTY"</langsyntaxhighlight>
 
==={{header|Batch FileBaCon}}===
The literal empty string in BaCon is <tt>""</tt>.
 
<syntaxhighlight lang="freebasic">' Empty string
<lang dos>
a$ = ""
IF a$ = "" THEN PRINT "Empty string"
IF a$ != "" THEN PRINT "Non empty string"</syntaxhighlight>
 
There are other ways, such as a zero return from the <tt>LEN(s$)</tt> or <tt>ULEN(utf$)</tt> functions. <tt>EQUAL(s$, "")</tt> would be another way.
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">subroutine IsEmpty (s$)
if length(s$) = 0 then
print "String is empty"
else
print "String is not empty"
end if
if s$ = "" then print "yes, the string is empty"
if s$ <> "" then print "no, the string is not empty"
end subroutine
 
t$ = ""
call IsEmpty (t$)
u$ = "not empty"
call IsEmpty (u$)
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 t$ = ""
120 isempty(t$)
130 u$ = "not empty"
140 isempty(u$)
150 end
160 sub isempty(s$)
170 if len(s$) = 0 then
180 print "String is empty"
190 else
200 print "String is not empty"
210 endif
220 if s$ = "" then print "yes, the string is empty"
230 if s$ <> "" then print "no, the string is not empty"
240 end sub</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">10 LET A$=""
20 IF A$="" THEN PRINT "The string is empty."
30 IF A$<>"" THEN PRINT "The string is not empty."</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|PC-BASIC}}
{{works with|QBasic}}
{{works with|Quite BASIC}}
<syntaxhighlight lang="qbasic">100 CLS : REM 100 HOME for Applesoft BASIC
110 LET S$ = ""
120 GOSUB 160
130 LET S$ = "not empty"
140 GOSUB 160
150 END
160 REM isEmpty
170 IF LEN(S$) = 0 THEN PRINT "String is empty"
180 IF LEN(S$) <> 0 THEN PRINT "String is not empty"
190 IF S$ = "" THEN PRINT "yes, the string is empty"
200 IF S$ <> "" THEN PRINT "no, the string is not empty"
210 RETURN</syntaxhighlight>
 
==={{header|QB64}}===
<syntaxhighlight lang="qb64">a$ = ""
If a$ = "" Then Print "Empty String"
If a$ <> "" Then Print a$ 'String is not empty, so print its contents.</syntaxhighlight>
 
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">SUB IsEmpty (s AS STRING)
IF LEN(s) = 0 THEN
PRINT "String is empty"
ELSE
PRINT "String is not empty"
END IF
IF s = "" THEN PRINT "yes, the string is empty"
IF s <> "" THEN PRINT "no, the string is not empty"
END SUB
 
DIM s AS STRING ' implicitly assigned an empty string
IsEmpty (s)
t$ = "" ' explicitly assigned an empty string
IsEmpty (t$)
u$ = "not empty"
IsEmpty (u$)</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">SUB IsEmpty(s$)
IF Len(s$) = 0 THEN
PRINT "String is empty"
ELSE
PRINT "String is not empty"
END IF
IF s$ = "" THEN PRINT "yes, the string is empty"
IF s$ <> "" THEN PRINT "no, the string is not empty"
END SUB
 
LET t$ = ""
CALL IsEmpty(t$)
LET u$ = "not empty"
CALL IsEmpty(u$)
END</syntaxhighlight>
 
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">t := ""
Print Show(FUNC(_IsEmpty(t)))
u := "not empty"
Print Show(FUNC(_IsEmpty(u)))
End
 
_IsEmpty Param (1) : Return (Join ("String is ", Iif(Len(a@), "not ", ""), "empty"))</syntaxhighlight>
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub IsEmpty (s$)
if len(s$) = 0 then
print "String is empty"
else
print "String is not empty"
endif
if s$ = "" print "yes, the string is empty"
if s$ <> "" print "no, the string is not empty"
end sub
 
t$ = ""
IsEmpty (t$)
u$ = "not empty"
IsEmpty (u$)
end</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
 
Line 198 ⟶ 655:
::Alternatively,
if %var%@ neq @ echo Var is not a blank string.
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> REM assign an empty string to a variable:
var$ = ""
Line 209 ⟶ 666:
REM Check that a string is not empty:
IF var$ <> "" THEN PRINT "String is not empty"
</syntaxhighlight>
</lang>
 
=={{header|Beef}}==
<syntaxhighlight lang="csharp">using System;
 
namespace EmptyString
{
class Program
{
public static void Main()
{
String s = scope .();
if (s.IsEmpty)
{
Console.Writeln("string empty");
}
if (!s.IsEmpty)
{
Console.Writeln("string not empty");
}
}
}
}
</syntaxhighlight>
 
=={{header|BQN}}==
An empty string in BQN is the same as an empty array, as all strings are character arrays.
 
To check emptiness, we can check the length of the array using <code>≠</code> (or shape with <code>≢</code>).
 
<syntaxhighlight lang="bqn">•Show ""
•Show 0 = ≠ ""
•Show 0 ≠ ≠ ""
•Show "" ≡ ⟨⟩</syntaxhighlight><syntaxhighlight lang="bqn">
⟨⟩
1
0
1</syntaxhighlight>
 
=={{header|Bracmat}}==
There are two ways to assign a string to a variable. The variant using the <code>=</code> operator does not evaluate the value before the assignment, the variant using the <code>:</code> (match) operator does. If the value is a string, there is no difference, as a string always evaluates to itself.
<langsyntaxhighlight lang="bracmat">( :?a
& (b=)
& abra:?c
Line 222 ⟶ 716:
& !d:~ { neither is d an empty string }
)
</syntaxhighlight>
</lang>
 
=={{header|Burlesque}}==
Line 228 ⟶ 722:
Empty string is <tt>""</tt> and checking for empty strings (or empty lists) can be done with the <tt>nu</tt> command.
 
<langsyntaxhighlight lang="blsq">
blsq ) ""
""
Line 235 ⟶ 729:
blsq ) "a"nu
0
</syntaxhighlight>
</lang>
 
=={{header|C}}==
In C the strings are <code>char</code> pointers. A string terminates with the null char (U+0000, <code>'\0'</code>), which is not considered part of the string. Thus an empty string is <code>"\0"</code>, while a null string is a null pointer which points to nothing.
<syntaxhighlight lang C="c">/* assign an empty#include <string */.h>
 
/* ... */
 
/* 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 */
/* or equivalently use strlen function
if (strlen(str) == 0) { ... }
strlen will seg fault on NULL pointer, so check first */
if ( (str == NULL) || (strlen(str) == 0)) { ... }
 
/* or compare to a known empty string, same thing. "== 0" means strings are equal */
if (strcmp(str, "") == 0) { ... }
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
class Program {
static void Main (string[] args) {
string example = string.Empty;
if (string.IsNullOrEmpty(example)) { }
if (!string.IsNullOrEmpty(example)) { }
}
}</syntaxhighlight>
 
===In depth===
'''Compiler:''' Roslyn C# (language version >= 6)
 
Note: implementation information provided in comments was obtained reflecting .NET libraries and viewing the .NET Core reference source and may not be correct or remain relevant as time passes.
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
static class Program
{
// In short:
public static void Foo()
{
string s;
 
// Assign empty string:
s = "";
// or
s = string.Empty;
 
// Check for empty string only (false if s is null):
if (s != null && s.Length == 0) { }
 
// Check for null or empty (more idiomatic in .NET):
if (string.IsNullOrEmpty(s)) { }
}
 
public static void Main()
{
// Equality is somewhat convoluted in .NET.
// The methods above are the author's recommendation for each case.
 
// s is initialized to null. It is a variable of the System.String type that is a null reference and is not
// the empty string.
string s = null;
 
// Alias Console.WriteLine(bool) with a shorter name to make the demonstration code less verbose.
Action<bool> P = Console.WriteLine;
 
// Assign the empty string literal to s.
s = "";
 
// ' Assign String.Empty to s.
s = string.Empty;
 
// The empty string literal is the same object reference as String.Empty because of string interning, meaning the
// behavior of the two is identical.
// From this point on, "" will be used instead of String.Empty for brevity.
 
//#== operator (object)
// The == operator tests for reference equality when overload resolution fails to find an operator defined by
// either operand type. However, which strings are interned is a CLR implementation detail and may be unreliable
// when comparing non-empty strings. The equivalent in VB.NET would be s Is "".
// Note that there is no such operator as Object.op_Equality(Object, Object): the use of the == operator for
// types of type Object is a C# language feature.
P((object)s == "");
 
//#Object.ReferenceEquals(Object, Object)
// The previous line is semantically to the following, though it does not involve a method call.
P(object.ReferenceEquals(s, ""));
 
//#String.op_Equality(String, String)
// The equality operator of System.String is implemented as a call to String.Equals(String). Operators cannot be
// called with method syntax in C#.
P(s == "");
 
//#String.Equals(String, String)
// Call the static method defined on the String type, which first calls Object.ReferenceEquals and then, after
// verifying that both are strings of the same length, compares the strings character-by-character.
P(string.Equals(s, ""));
 
//#Object.Equals(Object, Object)
// First checks for reference equality and whether one or both of the arguments is null. It then invokes the
// instance Equals method of the left parameter.
P(object.Equals(s, ""));
 
//#String.Equals(String)
// The method is called with the string literal as the receiver because a NullReferenceException is thrown if s
// is null.
P("".Equals(s));
 
//#String.Length
// Check the Length property. The ?. (null-conditional) operator is used to avoid NullReferenceException. The Equals
// call above can also be done this way. Null propagation makes the equality operator return false if one operand
// is a Nullable<T> and does not have a value, making this result in false when s is null.
P(s?.Length == 0);
 
//#String.Length
// A more traditional version of the null-conditional using a guard clause.
// Both the null-conditional and this are noticeably (~4 times) faster than "".Equals(s). In general, it appears that
// for empty strings, using the length is faster than using an equality comparison.
P(s != null && s.Length == 0);
 
//#String.IsNullOrEmpty(String)
// Note that all of the other methods give false for null.
// A static method of System.String that returns true if the string is null or its length is zero.
P(string.IsNullOrEmpty(s));
 
//#System.Collections.Generic.EqualityComparer(Of String).Default.Equals(String, String)
// The EqualityComparer(Of T) class provides default implementations when an IEqualityComparer(Of T) is required.
// The implementation for String calls String.Equals(String).
P(EqualityComparer<string>.Default.Equals(s, ""));
 
Console.WriteLine();
 
// Each of the means described above, except testing for a non-empty string.
P((object)s != "");
P(!object.ReferenceEquals(s, ""));
P(s != "");
P(!string.Equals(s, ""));
P(!object.Equals(s, ""));
P(!"".Equals(s));
P(s?.Length != 0); // Still false when s is null!
P(s == null || s.Length != 0);
P(!string.IsNullOrEmpty(s));
P(!EqualityComparer<string>.Default.Equals(s, ""));
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
 
// ...
 
 
std::string str; // a string object for an empty string
// empty string declaration
std::string str; // (default constructed)
std::string str(); // (default constructor, no parameters)
std::string str{}; // (default initialized)
std::string str(""); // (const char[] conversion)
std::string str{""}; // (const char[] initializer list)
 
 
 
if (str.empty()) { ... } // to test if string is empty
Line 262 ⟶ 903:
// we could also use the following
if (str.length() == 0) { ... }
if (str == "") { ... }</lang>
 
// make a std::string empty
=={{header|C sharp}}==
str.clear(); // (builtin clear function)
<lang csharp>using System;
str = ""; // replace contents with empty string
str = {}; // swap contents with temp string (empty),then destruct temp
 
// swap with empty string
class Program {
std::string tmp{}; static void Main// temp empty (string[] args) {
str.swap(tmp); // (builtin swap function)
string example = string.Empty;
std::swap(str, tmp); // swap contents with tmp
if (string.IsNullOrEmpty(example)) { }
 
if (!string.IsNullOrEmpty(example)) { }
 
}
// create an array of empty strings
}
std::string s_array[100]; // 100 initialized to "" (fixed size)
</lang>
std::array<std::string, 100> arr; // 100 initialized to "" (fixed size)
std::vector<std::string>(100,""); // 100 initialized to "" (variable size, 100 starting size)
 
// create empty string as default parameter
void func( std::string& s = {} ); // {} generated default std:string instance
</syntaxhighlight>
 
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">EMPTYSTR
; Demonstrate how to assign an empty string to a variable.
set x = ""
; Demonstrate how to check that a string is empty.
; Length 0 is empty; equality/pattern check are 1=T, 0=F
write !,"Assigned x to null value. Tests: "
write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."") ; length 0 is empty
; Demonstrate how to check that a string is not empty. Same as above.
set x = " " ;assign to a space - not null
write !!,"Assigned x to a single blank space. Tests: "
write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."")
quit</syntaxhighlight>
 
{{out}}SAMPLES>do EMPTYSTR^ROSETTA
 
Assigned x to null value. Tests:
String length: 0, Equals null: 1, Empty pattern: 1
 
Assigned x to a single blank space. Tests:
String length: 1, Equals null: 0, Empty pattern: 0
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(def x "") ;x is "globally" declared to be the empty string
(let [x ""]
Line 284 ⟶ 958:
(= x "") ;true if x is the empty string
(not= x "") ;true if x is not the empty string
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. EMPTYSTR.
Line 311 ⟶ 985:
 
STOP RUN.
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
Empty strings are mostly straightforward in CoffeeScript, but there's one gotcha.
 
<langsyntaxhighlight lang="coffeescript">
isEmptyString = (s) ->
# Returns true iff s is an empty string.
Line 329 ⟶ 1,003:
console.log (s = '') == "" # true
console.log new String() == '' # false, due to underlying JavaScript's distinction between objects and primitives
</syntaxhighlight>
</lang>
 
=={{header|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.
<langsyntaxhighlight 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>
;; (length s) returns zero for any empty sequence. You're better off using type checking:
(typep s '(string 0)) ;; only returns true on empty string
(typep s '(and string
(not (string 0))))) ;; only returns true on string that is not empty
</syntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE EmptyString;
IMPORT StdLog;
Line 362 ⟶ 1,041:
END Do;
END EmptyString.
</syntaxhighlight>
</lang>
Execute: ^Q EmptyString.Do<br/>
{{out}}
Line 372 ⟶ 1,051:
Is not 's' empty?:> $FALSE
</pre>
 
=={{header|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.
<langsyntaxhighlight lang="d">import std.array;
 
bool isEmptyNotNull(in string s) pure nothrow @safe {
Line 400 ⟶ 1,080:
assert(s1.empty);
assert(s2.isEmptyNotNull());
}</langsyntaxhighlight>
 
=={{header|Dart}}==
 
<langsyntaxhighlight lang="dart">main() {
var empty = '';
 
Line 414 ⟶ 1,094:
print('it is not empty');
}
}</langsyntaxhighlight>
=={{header|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>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program EmptyString;
 
{$APPTYPE CONSOLE}
Line 445 ⟶ 1,116:
s := 'abc';
Writeln(StringIsEmpty(s)); // False
end.</langsyntaxhighlight>
 
=={{header|Diego}}==
Assign an empty string to variable <code>s</code>.
<syntaxhighlight lang="diego">add_str(s,⟦⟧); // empty string
add_str(n); // null string (␀)</syntaxhighlight>
 
Check a string is empty (various approaches).
<syntaxhighlight lang="diego">add_str(es,⟦⟧);
add_bool(isEmpty)
()_check⟦[es]==⟦⟧⟧;
()_if⟦[es]≍⟦⟧⟧;
()_calc({bool},⟦[es]==⟦⟧⟧);
()_test⟦[lens]≍0⟧_lento(lens,⟦[es]⟧);
()_is⟦[lens]>0⟧_lento(lens,⟦[es]⟧);
()_check⟦[es]===({str},⟦⟧)⟧;
()_if⟦[es]≡({str},⟦⟧)⟧;
()_calc⟦≣[es]⟧_forme()_forall();
()_not⟦[es]≠⟦⟧⟧;
()_not()_bool[es];
()_empty[es];
(es)_equal⟦⟦⟧⟧;
;
log_console()_(isEmpty);
log_console()_is(es); // is not null</syntaxhighlight>
 
{{out}}
<pre>true,true,true,true,true,true,true,true,true,true,true,true
true</pre>
 
Check a string is not empty (various approaches).
<syntaxhighlight lang="diego">add_str(s,⟦text⟧);
add_bool(isNotEmpty)
()_check⟦[s]!=⟦⟧⟧;
()_if⟦[s]≭⟦⟧⟧;
()_calc({bool},⟦[s]≠⟦⟧⟧);
()_test⟦[lens]≠0⟧_lento(lens,⟦[s]⟧);
()_is⟦[lens]<0⟧_lento(lens,⟦[s]⟧);
()_check⟦[s]!==({str},⟦⟧)⟧;
()_if⟦[s]≢({str},⟦⟧)⟧;
()_calc⟦!≣[s]⟧_forme()_forany();
()_bool[s];
()_not()_empty[s];
(s)_notequal⟦⟦⟧⟧;
;
log_console()_(isNotEmpty);
log_console()_is(s); // is not null</syntaxhighlight>
 
{{out}}
<pre>true,true,true,true,true,true,true,true,true,true,true
true</pre>
 
Check a string is <code>null</code> (␀) (various approaches).
<syntaxhighlight lang="diego">add_str(n);
add_bool(isNull)
()_check⟦![n]⟧;
()_calc({bool},⟦¬[n]⟧);
()_isnull[n];
()_not[n];
()_isnull()_bool[n];
()_none[n];
()_any[n]_forme();
(n)_equal⟦␀⟧;
;
log_console()_(isNull);</syntaxhighlight>
 
{{out}}
<pre>true,true,true,true,true,true,true,true</pre>
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">var s : String;
 
s := ''; // assign an empty string (can also use "")
Line 458 ⟶ 1,196:
 
if s <> '' then
PrintLn('not empty');</langsyntaxhighlight>
 
=={{header|ElenaDyalect}}==
<lang elena>#import system.
#import extensions.
 
Demonstrate how to assign an empty string to a variable:
#symbol program = [
#var s := emptyLiteralValue.
 
<syntaxhighlight lang="dyalect">var str = ""</syntaxhighlight>
(s is &empty)
 
? [ console writeLine:"'":s:"' is empty". ].
Demonstrate how to check that a string is empty:
 
(s is &nonempty)
<syntaxhighlight lang="dyalect">if str.IsEmpty() { }</syntaxhighlight>
? [ console writeLine:"'":s:"' is not empty". ].
 
].</lang>
Demonstrate how to check that a string is not empty:
 
<syntaxhighlight lang="dyalect">if !str.IsEmpty() { }</syntaxhighlight>
 
=={{header|Déjà Vu}}==
Like in Python, empty strings are falsy, non-empty strings are truthy.
<syntaxhighlight lang="dejavu">local :e ""
 
if not e:
!print "an empty string"
 
if e:
!print "not an empty string"</syntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">a$ = ""
if a$ = ""
print "empty"
.
if a$ <> ""
print "no empty"
.</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x:
<syntaxhighlight lang="elena">import extensions;
public program()
{
auto s := emptyString;
if (s.isEmpty())
{ console.printLine("'", s, "' is empty") };
if (s.isNonempty())
{ console.printLine("'", s, "' is not empty") }
}</syntaxhighlight>
{{out}}
<pre>
'' is empty
</pre>
 
=={{header|Elixir}}==
To check whether a given variable holds an empty string, either compare it to the empty string literal, check its length - O(M), or check it's byte size - O(1)).
<langsyntaxhighlight lang="elixir">
empty_string = ""
not_empty_string = "a"
Line 493 ⟶ 1,270:
byte_size(not_empty_string) == 0
# => false
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(setq str "") ;; empty string literal
 
(if (= 0 (length str))
(message "string is empty"))
(if (/= 0 (length str))
(message "string is not empty"))</langsyntaxhighlight>
 
Also possible is <code>(string= "" str)</code>.
 
An common lisp incompatible way:
<syntaxhighlight lang="lisp">
(defvar str "" "An empty string")
 
(if (length= str 0)
(message "string is empty")
(message "string is not empty"))
</syntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
# Demonstrate how to assign an empty string to a variable.
text sampleA = Text.EMPTY
text sampleB = "hello world"
text sampleC = ""
List samples = text[sampleA, sampleB, sampleC]
for each text sample in samples
# Demonstrate how to check that a string is empty.
writeLine("Is '" + sample + "' empty? " + when(sample.isEmpty(), "Yes", "No") + ".")
end
</syntaxhighlight>
{{out}}
<pre>
Is '' empty? Yes.
Is 'hello world' empty? No.
Is '' empty? Yes.
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
1> S = "". % erlang strings are actually lists, so the empty string is the same as the empty list [].
[]
Line 515 ⟶ 1,320:
4> case "aoeu" of [] -> empty; [H|T] -> not_empty end.
not_empty
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">sequence s
 
-- assign an empty string
Line 532 ⟶ 1,337:
if length(s) then
-- string is not empty
end if</langsyntaxhighlight>
 
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
[<EntryPoint>]
Line 543 ⟶ 1,347:
printfn "Is empty %A: %A" emptyString (emptyString = String.Empty)
printfn "Is not empty %A: %A" emptyString (emptyString <> String.Empty)
0</langsyntaxhighlight>
{{out}}
<pre>Is empty "": true
Is not empty "": false</pre>
 
=={{header|Factor}}==
 
It's idiomatic in Factor to prefer using the stack over variable bindings.
 
<syntaxhighlight lang="factor">"" empty? .</syntaxhighlight>
{{out}}
<pre>
t
</pre>
 
However, Factor provides lexical variables:
 
<syntaxhighlight lang="factor">USE: locals
[let
"" :> empty-string
empty-string empty? .
empty-string empty? not .
]</syntaxhighlight>
{{out}}
<pre>
t
f
</pre>
 
=={{header|Fantom}}==
Line 552 ⟶ 1,380:
Fantom uses "" to represent an empty string, and provides the isEmpty method to check if a string is empty.
 
<langsyntaxhighlight lang="fantom">
a := "" // assign an empty string to 'a'
a.isEmpty // method on sys::Str to check if string is empty
Line 558 ⟶ 1,386:
a == "" // alternate check for an empty string
!a.isEmpty // check that a string is not empty
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Strings are represented as an addr-len pair on the stack. An empty string has len 0.
<langsyntaxhighlight 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
Line 569 ⟶ 1,397:
: filled? ( c-addr u -- ? ) empty? 0= ;
: ="" ( c-addr u -- ) drop 0 ; \ It's OK to copy syntax from other languages
</syntaxhighlight>
</lang>
 
Forth Console Test (True= -1, False=0)
Line 585 ⟶ 1,413:
 
Such variables, or text literals, may be passed as a parameter to a subprogram, and it may use the LEN function to ascertain the size of the parameter, which in that sense could be considered a string because CHARACTER parameters are passed with a secret additional parameter, their size, which is available to the LEN function within the subprogram.
<langsyntaxhighlight lang="fortran"> SUBROUTINE TASTE(T)
CHARACTER*(*) T !This form allows for any size.
IF (LEN(T).LE.0) WRITE(6,*) "Empty!"
Line 595 ⟶ 1,423:
TEXT = "" !Fills the entire variable with space characters.
CALL TASTE(TEXT) !Passes all 24 of them. Result is Not empty!
END</langsyntaxhighlight>
Otherwise, you could employ the Fortran protocol that trailing spaces are irrelevant in text comparisons. Thus <code>TEXT .EQ. ""</code> would give ''true'' even though TEXT might contain thousands of space characters, and so would <code>TEXT .EQ. " "</code> - thus an empty string is one containing nothing other than spaces.
 
Line 601 ⟶ 1,429:
 
With F90, compound data aggregates can be defined and as well procedures for operating on them, so that, after a great deal of syntactic struggle, a string data type will be available. F2000 standardised one such scheme whereby character variables are de-allocated and re-allocated with usage so that a statement such as <code>TEXT = "This" // "That"</code> would cause a de-allocation of whatever storage had been associated with TEXT followed by a re-allocation of storage for eight characters, the required size, and LEN(TEXT) would give 8.
 
=={{header|Free Pascal}}==
Assigning an empty string:
<syntaxhighlight lang="pascal">s := '';</syntaxhighlight>
Checking for an empty string:
<syntaxhighlight lang="pascal">s = ''
length(s) = 0</syntaxhighlight>
Checking for a non-empty string:
<syntaxhighlight lang="pascal">s <> ''
length(s) > 0
longBool(length(s))</syntaxhighlight>
The <code>sysUtils</code> unit defines the constants <code>emptyStr</code> and <code>emptyWideStr</code>, which can be used in place of <code>&#39;&#39;</code>.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub IsEmpty(s As String)
If Len(s) = 0 Then
Print "String is empty"
Else
Print "String is not empty"
End If
End Sub
 
Dim s As String ' implicitly assigned an empty string
IsEmpty(s)
Dim t As String = "" ' explicitly assigned an empty string
IsEmpty(t)
Dim u As String = "not empty"
IsEmpty(u)
Sleep</syntaxhighlight>
 
{{out}}
<pre>
String is empty
String is empty
String is not empty
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">a = ""
if a == ""
println["empty"]
 
if a != ""
println["Not empty"]</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"Empty string", (0,0,480,270)
FB has several ways to determine string length as demonstrated below.
Note: The length -- or number of characters -- of a Pascal string in FB is stored in the first element of the string array. Here the string is dimensioned a s, hence s[0] contains the length of the string, and any individual character in the string can be found using s[i], where i is the position of the character. This makes iterating over the individual characters in a string easier than using functions such as instr or mid$.
<lang futurebasic>
include "ConsoleWindow"
 
CFStringRef s
dim as Str255 s
 
s = @""
if s( ==fn StringIsEqual( s, @"" ) ) then print @"Stringstring is empty"
if ( fn StringLength( s[0] ) == 0 ) then print @"Stringstring is empty"
if ( len(s) == 0 ) then print @"Stringstring is empty"
 
print
s = "Hello"
 
if s <> "" then print "String not empty."
s = @"Hello"
if s[0] then print "String not empty."
if len( fn StringIsEqual( s, @"" ) >== 0NO ) then print @"Stringstring not empty."
if ( fn StringLength( s ) != 0 ) then print @"string not empty"
</lang>
if ( len(s) != 0 ) then print @"string not empty"
 
HandleEvents</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=4d8a208f49364dc25361bf2042af1005 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sString As String[] = ["", "Hello", "world", "", "Today", "Tomorrow", "", "", "End!"]
Dim sTemp As String
Dim siCount As Short
 
For Each sTemp In sString
If sString[siCount] Then
Print "String " & siCount & " = " & sString[siCount]
Else
Print "String " & siCount & " is empty"
End If
Inc siCount
Next
 
End</syntaxhighlight>
Output:
<pre>
String 0 is empty
String 1 = Hello
String 2 = world
String 3 is empty
String 4 = Today
String 5 = Tomorrow
String 6 is empty
String 7 is empty
String 8 = End!
</pre>
 
=={{header|Go}}==
Line 625 ⟶ 1,529:
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.
<langsyntaxhighlight lang="go">// define and initialize an empty string
var s string
s2 := ""
Line 638 ⟶ 1,542:
// check that a string is not empty, any of:
s != ""
len(s) != 0 // or > 0</langsyntaxhighlight>
::<syntaxhighlight lang="go">package main
 
import (
"fmt"
)
 
func test(s string) {
if len(s) == 0 {
fmt.Println("empty")
} else {
fmt.Println("not empty")
}
}
 
func main() {
// assign an empty string to a variable.
str1 := ""
str2 := " "
// check if a string is empty.
test(str1) // prt empty
// check that a string is not empty.
test(str2) // prt not empty
}</syntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def s = '' // or "" if you wish
assert s.empty
 
s = '1 is the loneliest number'
assert !s.empty</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang="gwbasic">10 DIM S1$ 'implicitly defined empty string
20 S2$ = "" 'explicitly defined empty string
30 S3$ = "Foo bar baz"
40 S$=S1$ : GOSUB 200
50 S$=S2$ : GOSUB 200
60 S$=S3$ : GOSUB 200
70 END
200 IF LEN(S$)=0 THEN PRINT "Empty string" ELSE PRINT "Non-empty string"
210 RETURN</syntaxhighlight>
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">// in Harbour we have several functions to check emptiness of a string, f.e. hb_IsNull(), Len(), Empty() et.c.,
// we can also use comparison expressions like [cString == ""] and [cString != ""], yet the most convenient
// of them is `Empty()` (but that depends on personal coding style).
cString := ""
? Empty( cString ) // --> TRUE
IF ! Empty( cString ) // --> FALSE
? cString
ENDIF</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad
 
-- In Haskell strings are just lists (of characters), so we can use the function
Line 657 ⟶ 1,605:
let s = ""
when (null s) (putStrLn "Empty.")
when (not $ null s) (putStrLn "Not empty.")</langsyntaxhighlight>
 
=={{header|HolyC}}==
<syntaxhighlight lang="holyc">/* assign an empty string */
U8 *str = StrNew("");
/* or */
U8 *str = "";
 
/* to test if string is empty */
if (StrLen(str) == 0) { ... }
/* or compare to a known empty string. "== 0" means strings are equal */
if (StrCmp(str, "") == 0) { ... }
 
/* to test if string is not empty */
if (StrLen(str)) { ... }</syntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">software {
s = ""
// Can either compare the string to an empty string or
// test if the length is zero.
if s = "" or #s = 0
print("Empty string!")
end
if s - "" or #s - 0
print("Not an empty string!")
end
}
</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon can produce empty strings in several ways:
<langsyntaxhighlight Iconlang="icon">s := "" # null string
s := string('A'--'A') # ... converted from cset difference
s := char(0)[0:0] # ... by slicing
Line 676 ⟶ 1,654:
s := &null # NOT a null string, null type
/s # test for null type
\s # test for non-null type </langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j"> variable=: ''
0=#variable
1
0<#variable
0</langsyntaxhighlight>
 
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 <code>if.</code> or <code>while.</code> statement, J treats an empty string (or the absence of any argument) as true.
 
In this context, it's also worth noting that J has concepts of emptiness which are emptier than an empty string. For
example:
 
<syntaxhighlight lang="j"> ''
 
EMPTY
$''
0
$EMPTY
0 0</syntaxhighlight>
 
Here, the display of an empty string occupies one line (just like the display of any other string -- except this line is an empty line), while the display of <code>EMPTY</code> occupies zero blank lines. Or <code>EMPTY</code> contains zero empty strings (or zero empty lists). When you want the result of a J verb to not display any result, use a value like EMPTY as its explicit result.
 
=={{header|Java}}==
<code>String.isEmpty()</code> is part of Java 1.6. Other options for previous versions are noted.
<langsyntaxhighlight 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");
}</langsyntaxhighlight>
 
 
=={{header|JavaScript}}==
Create an empty String
<langsyntaxhighlight lang="javascript">var s = "";
var s = new String();</langsyntaxhighlight>
 
Boolean expressions representing emptiness
<langsyntaxhighlight lang="javascript">s == ""
s.length == 0
!s
!Boolean(s)</langsyntaxhighlight>
 
Non-emptiness
<langsyntaxhighlight lang="javascript">!!s
s != ""
s.length != 0
s.length > 0
Boolean(s)</langsyntaxhighlight>
 
=={{header|jq}}==
jq programs can read JSON strings as data and may contain JSON strings. This entry is focused on such strings and excludes from consideration interpolation directives, which have the form of strings but are not themselves valid JSON strings.
jq strings are JSON strings. The empty string literal is simply <tt>""</tt>. 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.
 
The empty string literal is simply <tt>""</tt>. It can be assigned to a variable as illustrated by this example:<syntaxhighlight lang="jq">"" as $x </syntaxhighlight>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 == ""
 
To determine whether a string, s, is empty:<syntaxhighlight lang="jq">s == ""
# or:
s|length == 0</langsyntaxhighlight>To determine whether a string, s, is non-empty:<langsyntaxhighlight lang="jq">s != ""
# or:
s.length != 0 # etc.</langsyntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Empty string, in Jsish */
var em1 = '';
var em2 = new String();
 
var str = 'non-empty';
 
;'Empty string tests';
;em1 == '';
;em1 === '';
;em1.length == 0;
;!em1;
;(em1) ? false : true;
;Object.is(em1, '');
;Object.is(em1, new String());
 
;'Non empty string tests';
;str != '';
;str !== '';
;str.length != 0;
;str.length > 0;
;!!str;
;(str) ? true : false;
 
;'Compare two empty strings';
;(em1 == em2);
;(em1 === em2);
 
/*
=!EXPECTSTART!=
'Empty string tests'
em1 == '' ==> true
em1 === '' ==> true
em1.length == 0 ==> true
!em1 ==> true
(em1) ? false : true ==> true
Object.is(em1, '') ==> true
Object.is(em1, new String()) ==> true
'Non empty string tests'
str != '' ==> true
str !== '' ==> true
str.length != 0 ==> true
str.length > 0 ==> true
!!str ==> true
(str) ? true : false ==> true
'Compare two empty strings'
(em1 == em2) ==> true
(em1 === em2) ==> true
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish --U emptyString.jsi
'Empty string tests'
em1 == '' ==> true
em1 === '' ==> true
em1.length == 0 ==> true
!em1 ==> true
(em1) ? false : true ==> true
Object.is(em1, '') ==> true
Object.is(em1, new String()) ==> true
'Non empty string tests'
str != '' ==> true
str !== '' ==> true
str.length != 0 ==> true
str.length > 0 ==> true
!!str ==> true
(str) ? true : false ==> true
'Compare two empty strings'
(em1 == em2) ==> true
(em1 === em2) ==> true
 
prompt$ jsish -u emptyString.jsi
[PASS] emptyString.jsi</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
blank = ""
nonblank = "!"
Line 742 ⟶ 1,809:
println("That nonblank is empty is ", isempty(nonblank))
println("That nonblank is not empty is ", !isempty(nonblank))
</syntaxhighlight>
</lang>
 
{{out}}
Line 758 ⟶ 1,825:
{{trans|J}}
 
<langsyntaxhighlight Klang="k"> variable: ""
0=#variable
1
0<#variable
0</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
<lang scala>val s = ""
val s = ""
println(s.isEmpty()) // true
println(s.isNotEmptyisEmpty()) // falsetrue
println(s.lengthisNotEmpty()) // 0false
println(s.none()length) // true0
println(s.anynone()) // false</lang>true
println(s.any()) // false
}</syntaxhighlight>
 
=={{header|LabVIEW}}==
{{VI solution|LabVIEW_Empty_string.png}}
 
=={{header|Lambdatalk}}==
In Lambdatalk primitives working on sequences of words begin with "S."
<syntaxhighlight lang="scheme">
'{def emptyString }
-> emptyString
 
'{S.empty? {emptyString}}
-> true
 
'{S.empty? hello}
-> false
 
'{= {S.length {emptyString}} 0}
-> true
</syntaxhighlight>
 
 
=={{header|Lang}}==
In Lang strings are called text and are of type TEXT.
<syntaxhighlight lang="lang">
# Text creation
# Empty text escape sequence
$s = \e
$s = {{{}}}
# With simple assignment:
$s=
 
# "$s =" would not work, as ist would set $s to null
 
# Is empty
fn.println(parser.con($s == \e))
fn.println(parser.con($s === \e))
fn.println(parser.con(!$s))
fn.println(fn.conNot($s))
fn.println(parser.con(fn.strlen($s) == 0))
fn.println(parser.con(fn.len($s) == 0))
fn.println(parser.op(@$s == 0))
 
# Is not empty
fn.println(parser.con($s != \e))
fn.println(parser.con($s !== \e))
fn.println(parser.con($s)) # Must be used in conditional parsing mode (Execution parsing mode would return $s as is)
fn.println(fn.bool($s))
fn.println(parser.con(fn.strlen($s) > 0))
fn.println(parser.con(fn.len($s) > 0))
fn.println(parser.op(@$s > 0))
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">//Demonstrate how to assign an empty string to a variable.
local(str = string)
local(str = '')
Line 787 ⟶ 1,904:
local(str = 'Hello, World!')
#str->size > 0 // true
#str->size // true</langsyntaxhighlight>
 
=={{header|Latitude}}==
 
Assigning the empty string.
<syntaxhighlight lang="latitude">s := "".
s := String clone.</syntaxhighlight>
 
Checking whether a string is empty.
<syntaxhighlight lang="latitude">s == "".
s empty?.
s length == 0.</syntaxhighlight>
 
Note that all strings are truthy in Latitude, so simply checking the truthiness of a string is an insufficient means to check whether it is empty.
 
=={{header|LFE}}==
Line 794 ⟶ 1,924:
{{trans|Erlang}}
 
<langsyntaxhighlight lang="lisp">
> (set str "")
()
Line 819 ⟶ 1,949:
> (case "apple" ('() 'empty) ((cons head tail) 'not-empty))
not-empty
</syntaxhighlight>
</lang>
 
=={{header|Lhogho}}==
Lhogho is a Logo compiler for Windows and Linux
<langsyntaxhighlight lang="logo">make "str " ;make null-string word
print empty? :str ;prints 'true'
print not empty? :str ;prints 'false'
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'assign empty string to variable
a$ = ""
Line 838 ⟶ 1,968:
if a$<>"" then print "Not empty."
if len(a$)>0 then print "Not empty."
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">str = EMPTY -- same as: str = ""
put str=EMPTY
-- 1
put str<>EMPTY
-- 0</syntaxhighlight>
 
=={{header|LOLCODE}}==
The empty string is a false value in LOLCODE, and is thus amenable to use as the condition of an <tt>O RLY?</tt>
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A string ITZ ""
Line 850 ⟶ 1,987:
OIC
 
KTHXBYE</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>str = "" -- create empty string
-- create an empty string 3 different ways
str = ""
str = ''
str = [[]]
 
-- test for empty string
Line 863 ⟶ 2,004:
if str ~= "" then
print "The string is not empty"
end</lang>
 
-- several different ways to check the string's length
if string.len(str) == 0 then
print "The library function says the string is empty."
end
if str:len() == 0 then
print "The method call says the string is empty."
end
if #str == 0 then
print "The unary operator says the string is empty."
end
 
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Easy reply for this task
<syntaxhighlight lang="m2000 interpreter">
A$=""
Print A$<>"", A$="", Len(A$)=0
</syntaxhighlight>
 
Depends of variable visibility, and what we want to do: To make a new local, to shadow a local or a global on.
 
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
\\
\\ Part 1: Make global variable, alter it, make a shadow local or global one, use temporary variable
\\
Global a$="ok"
Module Global What {
Print a$
}
Module Checkit {
Print a$="ok"
a$<=""
Print a$=""
a$<="ok2"
a$=""
Print a$="", a$<>""
Global a$="ok again"
Module Inner {
Print a$="ok again"
}
Inner
What \\ now What use new global a$
\\ display list of public variables
List
\\ we can define locals using Def, but raise error if local exist
Try {
Def a$="error"
}
Def b$
Print b$=""
For This {
\\ block for temporary definitions
For i=1 to 10 {
Local a$=str$(i)
}
\\ we get 10 more a$
List
Print a$=" 10"
}
Print a$=""
List
\\ using current stack
}
\\ we call always a local module, or a global, but not this module,
\\ no recursion for standard call for modules.
\\ we have to use Call Checkit to call this module recursive
Checkit
What \\ now what use old global a$
Print a$<>"" ' true
List
\\
\\ Part 2: Pass an empty string to a variable through stack of values
\\
Module Checkit2 {
\\ read make a local by default
Read a$
Print a$="" ' true
For This {
Push "Hello"
Read New a$
Print a$="Hello"
List
}
Print a$=""
}
Checkit2 ""
Print a$<>"" ' true
Module Checkit3 {
\\ using Set we change to global space, for the end of line
Set Read a$
Print a$="" ' true
list
}
Checkit3 ""
Print a$<>"" ' true
Module Checkit4 {
\\ this make a local if no global exist
\\ so if global exist, alter the global one
Let a$=Letter$
Print a$="" ' true
list
}
Checkit4 ""
Print a$="" ' true
}
Checkit
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight 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
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
str=""; (*Create*)
str==="" (*test empty*)
str=!="" (*test not empty*)
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab"> % Demonstrate how to assign an empty string to a variable.
str = '';
% Demonstrate how to check that a string is empty.
Line 888 ⟶ 2,140:
% Demonstrate how to check that a string is not empty.
~isempty(str)
(length(str)>0)</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">s: ""$
 
/* check using string contents */
Line 899 ⟶ 2,151:
/* check using string length */
slength(s) = "";
slength(s) # "";</langsyntaxhighlight>
 
=={{header|Mercury}}==
 
There's nothing special about empty strings in Mercury.
 
<syntaxhighlight lang="mercury">S = "", % assignment
 
( if S = "" then ... else ... ), % checking if a string is empty
 
( if not S = "" then ... else ... ), % checking if a string is not empty</syntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
The <code>bool</code> operator returns <code>false</code> on an empty string and <code>true</code> on a non-empty string. We can define <code>empty?</code> as the negation of <code>bool</code>.
<syntaxhighlight lang="min">(bool not) :empty?
"" empty? puts!
"Rosetta Code" empty? puts!</syntaxhighlight>
{{out}}
<pre>
true
false
</pre>
 
=={{header|MiniScript}}==
{{trans|Wren}}
<syntaxhighlight lang="miniscript">string.isEmpty = function
return self == ""
end function
 
number.toBoolStr = function
if self == 0 then return "false"
return "true"
end function
 
s = ""
t = "0"
print "'s' is empty? " + s.isEmpty.toBoolStr
print "'t' is empty? " + t.isEmpty.toBoolStr</syntaxhighlight>
 
{{out}}
<pre>'s' is empty? true
't' is empty? false
</pre>
 
=={{header|MIPS Assembly}}==
An empty string is just a null terminator with nothing in front of it.
 
Storing an empty string:
<syntaxhighlight lang="mips">li t0,0
la a0,UserRam
sb t0,(a0)</syntaxhighlight>
 
Checking that a string is (not) empty:
 
<syntaxhighlight lang="mips">lbu t0,(a0)
nop ;load delay slot (only necessary on MIPS I hardware)
beqz t0,StringIsEmpty
nop ;branch delay slot
 
;your code for what happens when the string is not empty, goes here</syntaxhighlight>
 
=={{header|Mirah}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE EmptyString EXPORTS Main;
 
IMPORT IO,Text;
 
VAR
Str:TEXT;
BEGIN
(* Assign an empty string *)
Str := "";
(* Check if Str is empty *)
IF Text.Empty(Str) THEN
IO.Put("Str is empty!\n");
END;
(* Same as above: *)
IF Text.Length(Str) = 0 THEN
IO.Put("Str is empty!\n");
END;
(* To check for a non-empty string, negate any of the above
conditions with NOT *)
END EmptyString.</syntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">s = ""
 
if len(s)=0
println "s is empty"
else
println "s is not empty"
end</syntaxhighlight>
 
=={{header|Nemerle}}==
Assign an empty string:
<langsyntaxhighlight Nemerlelang="nemerle">def empty = "";
mutable fill_later = "";</langsyntaxhighlight>
Check if a string is empty/not empty:
<langsyntaxhighlight Nemerlelang="nemerle">a_string == ""; a_string != 0;
a_string.Length == 0; a_string.Length > 0;</langsyntaxhighlight>
 
=={{header|NESL}}==
<syntaxhighlight lang="nesl">my_empty_string = "";
 
% To make sure it is empty, we can ask whether its length is equal to zero. %
 
#my_empty_string == 0;</syntaxhighlight>
{{out}}
<pre>my_empty_string = "" : [char]
 
it = T : bool</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 939 ⟶ 2,293:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 949 ⟶ 2,303:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var x = ""
 
if x == "":
Line 960 ⟶ 2,314:
echo "empty"
if x.len > 0:
echo "not empty"</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 S$=""
20 IF S$<>"" THEN O$="NOT "
30 PRINT "THE STRING IS "O$"EMPTY."</syntaxhighlight>
 
=={{header|Nyquist}}==
===Lisp Syntax===
<syntaxhighlight lang="lisp">
(setf emptystring "") ;binds variable'emptystring' to the empty string ""
 
(let ((emptystring "")) ;; Binds local variable 'emptystring' to the empty string ""
(when (string-equal emptystring "") ;;case insensitive string comparison
(print "Is an empty string")) ;;bad argument error if not a string
(when (stringp emptystring)
(print "Is a string"))
(when (not (stringp emptystring))
(print "Is not a string"))
(when (and (stringp emptystring)(= (length emptystring) 0))
(print "Is an empty string"))
(when (and (stringp emptystring)(> (length emptystring) 0))
(print "Is a non-empty string")))
</syntaxhighlight>
 
===SAL Syntax===
<syntaxhighlight lang="sal">
define variable emptystring = "" ;binds variable'emptystring' to the empty string ""
 
if emptystring = "" then
print "is empty string"
else
print "is not empty string"
</syntaxhighlight>
 
 
===Audacity plug-in (LISP syntax)===
<syntaxhighlight lang="lisp">
;nyquist plug-in
;version 4
;type tool
;name "Empty string"
 
(setq emptystring "") ;; Define global variable
 
(if (string= emptystring "") ;;case sensitive string comparison
"The string is empty."
"The string is not empty.")
</syntaxhighlight>
 
 
===Audacity plug-in (SAL syntax)===
<syntaxhighlight lang="nyquist">
;nyquist plug-in
;version 4
;codetype sal
;type tool
;name "Empty string"
 
define variable emptystring = "a" ;; Define global variable
 
;; The ternary operator is #?
return #?(emptystring = "",
"The string is empty.",
"The string is not empty.")
</syntaxhighlight>
 
=={{header|oberon-2}}==
{{works with|oo2c version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE EmptyString;
IMPORT Out;
Line 979 ⟶ 2,398:
Out.String("checking str[0] = 0X. Is Empty? ");Out.Bool(str[0] = 0X);Out.Ln;
END EmptyString.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 991 ⟶ 2,410:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
s := "";
if(s->IsEmpty()) {
Line 998 ⟶ 2,417:
"s is not empty"->PrintLine();
};
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let is_string_empty s =
(s = "")
 
Line 1,010 ⟶ 2,429:
Printf.printf "s1 empty? %B\n" (is_string_empty s1);
Printf.printf "s2 empty? %B\n" (is_string_empty s2);
;;</langsyntaxhighlight>
 
{{out}}
Line 1,022 ⟶ 2,441:
isEmpty can be used on all collections, not only strings.
 
<langsyntaxhighlight Oforthlang="oforth">"" isEmpty
"" isEmpty not</langsyntaxhighlight>
 
=={{header|OpenEdge/ProgressOl}}==
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.
 
<syntaxhighlight lang="ol">
<lang progress>DEFINE VARIABLE cc AS CHARACTER.
; define the empty string
(define empty-string "")
 
; three simplest tests for 'the-string emptiness
IF cc > '' THEN
(if (or
MESSAGE 'not empty' VIEW-AS ALERT-BOX.
(string-eq? the-string "")
ELSE IF cc = ? THEN
(string=? the-string "")
MESSAGE 'unknown' VIEW-AS ALERT-BOX.
(eq? (string-length the-string) 0))
ELSE /* IF cc = '' */
(print "the-string is empty")
MESSAGE 'empty' VIEW-AS ALERT-BOX.
 
</lang>
; four simplest tests for 'the-string not emptiness
(if (or
(not (string-eq? the-string ""))
(not (string=? the-string ""))
(not (eq? (string-length the-string) 0))
(less? 0 (string-length the-string)))
(print "the-string is NOT empty))
</syntaxhighlight>
 
=={{header|ooRexx}}==
should work with each and every REXX interpreter/compiler.
<langsyntaxhighlight lang="oorexx">v=''
w=' '
if v=='' Then Say 'v contains the empty string'<
If length(w)>0 Then Say 'Variable w does not contain the empty string'
If w='' Then Say 'this is not a good test' </langsyntaxhighlight>
{{out}}
<pre>v contains the empty string
Variable w does not contain the empty string
this is not a good test</pre>
 
=={{header|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.
 
<syntaxhighlight 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.
</syntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">a="";
isEmpty(s)=s=="" \\ Alternately:
isEmpty(s)=#s==0
isNonempty(s)=s!="" \\ Alternatively:
isNonempty(s)=#s</langsyntaxhighlight>
 
=={{header|Pascal}}==
''See also [[Empty_string#Delphi|Delphi]] or [[#Free Pascal|Free DelphiPascal]]''
{{works with|Extended Pascal}}
<syntaxhighlight lang="pascal">program emptyString(output);
var
s: string(20);
begin
{ assigning an empty string }
s := '';
{ checking for an empty string }
writeLn( 'EQ(s, '''') :':20, EQ(s, ''):6);
writeLn( 'length(s) = 0 :':20, length(s) = 0:6);
{ checking that a string is not empty }
writeLn( 'NE(s, '''') :':20, NE(s, ''):6);
writeLn( 'length(s) > 0 :':20, length(s) > 0:6);
{ Beware: Only the string comparison functions (`EQ`, `NE`, etc.) take }
{ the string’s length into account. The symbolic `=` equal comparison }
{ operator, however, will pad operands with blanks to the same common }
{ length, and _subsequently_ compare individual string components. }
writeLn('!!! s = '' '' :':20, s = ' ':6);
{ If you want to perform the empty string check with an `=` comparison, }
{ you will need to call `trim` (remove trailing blanks) first. }
writeLn('trim(s) = '''' :':20, trim(s) = '':6)
end.</syntaxhighlight>
{{out}}
EQ(s, '&#39;) : True
length(s) = 0 : True
NE(s, '&#39;) : False
length(s) > 0 : False
!!! s = ' ' : True
trim(s) = '&#39; : True
 
=={{header|Perl}}==
<langsyntaxhighlight 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";
}</langsyntaxhighlight>
 
In Perl, an empty string is often used to represent a false value.
<langsyntaxhighlight Perllang="perl">$s = "";
if ($s) { ... } # false
 
Line 1,082 ⟶ 2,555:
# but a string that converts to number 0 is not always false, though:
$s = "0 but true";
if ($s) { ... } # it's true! black magic!</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
<lang perl6>my $s = '';
say 'String is empty' unless $s;
say 'String is not empty' if $s;</lang>
 
Unlike in Perl 5, only empty strings test as false - the string "0" tests as true now.
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang euphoria>string s
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span> <span style="color: #000080;font-style:italic;">-- assign an empty string</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- string is empty</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- string is empty</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- string is not empty</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- string is not empty</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
s = "" -- assign an empty string
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Empty_string
by Galileo, 10/2022 #/
 
"" var s
if length(s)=0 then -- string is empty
s len if "String is NOT empty" else "String IS empty" endif print nl
if s="" then -- string is empty
" " "" == if "String IS empty" else "String is NOT empty" endif print
 
</syntaxhighlight>
if length(s)!=0 then -- string is not empty
{{out}}
if s!="" then -- string is not empty</lang>
<pre>String IS empty
String is NOT empty
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight Phplang="php"><?php
 
$str = ''; // assign an empty string to a variable
Line 1,119 ⟶ 2,601:
 
if (strlen($str) == 0) { ... }
if (strlen($str) != 0) { ... }</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
S = "", % assign an empty string to a variable
S == "", % check that a string is empty,
"not empty" != "". % check that a string is not empty</syntaxhighlight>
 
In Picat a string is a list of characters so list notation can be also be used.
<syntaxhighlight lang="picat">main =>
S = "", % assign an empty string to a variable
S == [], % check that a string is empty,
"not empty" != []. % check that a string is not empty</syntaxhighlight>
 
=={{header|PicoLisp}}==
The empty string is represented by '[http://software-lab.de/doc/ref.html#nilSym NIL]' in PicoLisp. During input, two subsequent double quotes '""' return the symbol NIL.
<langsyntaxhighlight PicoLisplang="picolisp"># To assign a variable an empty string:
(off String)
(setq String "")
Line 1,136 ⟶ 2,630:
(and String ..)
(if String ..)
(when String ..)</langsyntaxhighlight>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">int main() {
string s;
 
if (!s == 1 || sizeof(s) == 0 || s == "") {
write("String is empty\n");
}
else {
write("String not empty\n");
}
 
return 0;
}</syntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">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 */
</syntaxhighlight>
</lang>
 
=={{header|PowerShellPlain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Put "" into a string.
If the string is blank, write "Empty!" on the console.
If the string is not blank, write "Not empty!" on the console.
Wait for the escape key.
Shut down.</syntaxhighlight>
 
=={{works withheader|PowerShell|4.0}}==
Assignment (the type identifier is optional):
<lang PowerShell>
<syntaxhighlight lang="powershell">
[string]::IsNullOrEmpty("")
[string]$alpha = "abcdefghijklmnopqrstuvwxyz"
[string]::IsNullOrEmpty("a")
[string]$empty = ""
</lang>
# or...
<b>Output:</b>
[string]$empty = [String]::Empty
</syntaxhighlight>
Tests:
<syntaxhighlight lang="powershell">
[String]::IsNullOrEmpty($alpha)
[String]::IsNullOrEmpty($empty)
</syntaxhighlight>
{{Out}}
<pre>
True
False
True
</pre>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|7}}
<langsyntaxhighlight lang="prolog">assign_empty_string(Variable) :- Variable = "".
 
is_empty_string(String) :- String == "".
not_empty_string(String) :- String \== "".
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
In PureBasic we can just test a string for truth to determine if it has a value.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s isStringEmpty(a.s)
If a
ProcedureReturn "String is not empty, it contains '" + a + "'."
Line 1,184 ⟶ 2,707:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>String is empty, or null.
Line 1,190 ⟶ 2,713:
 
=={{header|Python}}==
The empty string is printed by Python REPL as <nowiki>''</nowiki>, 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.
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>
 
<syntaxhighlight lang="python">
=={{header|R}}==
s = ''
# or:
s = str()
 
<langif not s or R>s <-== '':
print("String is empty")
 
if len(s) == 0:
print("String is empty")
else:
print("String not empty")
 
 
# boolean test function for python2 and python3
# test for regular (non-unicode) strings
# unicode strings
# None
def emptystring(s):
if isinstance(s, (''.__class__ , u''.__class__) ):
if len(s) == 0:
return True
else
return False
 
elif s is None:
return True
</syntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang="qbasic">Dim s1 As String 'initialized empty
If Len(s1) = 0 Then Print "Empty"
 
s2$ = ""
If s2$ = "" Then Print "Empty"
 
s3$ = "cat"
If Len(s3$) <> 0 Then Print "Not empty"
If s3$ <> "" Then Print "Still not empty"</syntaxhighlight>
{{out}}
<pre>
Empty
Empty
Not empty
Still not empty
</pre>
 
=={{header|Quackery}}==
Quackery does not have variables or assignment. The closest equivalent to variables is its ancillary stacks. ''temp'' is a predefined ancillary stack. Rather than assigning an empty string to a variable, we can create an empty string and move it to ''temp''.
 
Demonstrated as a dialogue in the Quackery REPL.
 
<syntaxhighlight lang="quackery">Welcome to Quackery.
 
Enter "leave" to leave the shell.
 
/O> $ "" temp put ( move an empty string to temp )
... temp share ( copy the empty string on temp to the stack )
... $ '' = ( compare the top of stack to an empty string, and replace it with
... 1 (true) if it is an empty string and 0 (false) if it is not. )
... temp take ( move the empty string on temp to the stack )
... $ '' != ( compare the top of stack to an empty string, and replace it with
... 1 (true) if it is not an empty string and 0 (false) if it is. )
...
 
Stack: 1 0
 
/O> leave
...
 
Aloha.</syntaxhighlight>
 
=={{header|Quite BASIC}}==
<syntaxhighlight lang="quite basic">10 let s=""
20 if s="" then let o=""
30 if s<>"" then let o="not "
40 print "The string is ";o;"empty."</syntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="r">s <- ''
 
if (s == '') cat('Empty\n')
Line 1,207 ⟶ 2,803:
if (s != '') cat('Not empty\n')
#or
if (nchar(s) > 0) cat('Not empty\n')</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define empty-string "")
(define (string-null? s) (string=? "" s))
(define (string-not-null? s) (string<? "" s))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>my $s = '';
say 'String is empty' unless $s;
say 'String is not empty' if $s;</syntaxhighlight>
 
Unlike in Perl 5, only empty strings test as false - the string "0" tests as true now.
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">str s = "";
if (s=="") print("string s is empty");
if (s!="") print("string s is not empty");
</syntaxhighlight>
</lang>
Or the build-in operator:
<langsyntaxhighlight lang="rascal">import String;
if (isEmpty(s)) print("string s is empty");
if (isEmpty(s)) print("string s is not empty");</langsyntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red []
s: copy "" ;; assign empty string
?? s
if empty? s [print "string is empty "] ;; check if string is empty
s: "abc"
prin s unless empty? s [print " not empty"]
</syntaxhighlight>
{{out}}
<pre>s: ""
string is empty
abc not empty
>>
</pre>
 
=={{header|Retro}}==
Create an empty string and assign it to a variable. In these '''keepString''' is used to ensure that the string is permanent.
<syntaxhighlight lang="retro">
 
<lang Retro>
( by creating a variable )
"" keepString variable: foo
Line 1,236 ⟶ 2,855:
( by setting an existing variable 'foo' )
"" keepString !foo
</syntaxhighlight>
</lang>
 
Checking that a string is empty. A string with a length of zero is assumed to be empty.
 
<syntaxhighlight lang="retro">
<lang Retro>
: emtpy? ( $-f ) getLength 0 = ;
 
"" empty? putn
"hello" empty? putn
</syntaxhighlight>
</lang>
 
Check that a string is not empty.
 
<syntaxhighlight lang="retro">
<lang Retro>
: notEmpty? ( $-f ) getLength 0 > ;
 
"" notEmpty? putn
"hello" notEmpty? putn
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program shows how to assign an empty string, & then check for empty/not-empty str*/
 
/*─────────────── 3 simple ways to assign an empty string to a variable.*/
Line 1,295 ⟶ 2,914:
if length(cod)\=0 then fish=cod /*a not-as-fast compare. */
 
/*────────────────────────── anyway, as they say: "choose your poison." */</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
cStr = NULL # empty string
if cStr = NULL
Line 1,305 ⟶ 2,924:
see "cstr is not empty string!" + nl
ok
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
<syntaxhighlight lang="robotic">
set "$string" to ""
if "$string.length" = 0 then "empty"
* "Not an empty string."
end
 
: "empty"
* "Empty string"
end
</syntaxhighlight>
 
=={{header|RPL}}==
===Assigning an empty string to a variable===
Here, s1 is a temporary variable that disappears at execution end: the <code>→</code> instruction both declares the variable and transfers the value at stack level 1 into it. <code>STO</code> does the same, but the syntax is different (instruction after the variable name) and the created variable is persistent.
≪ "" → s1
≪ "" 's2' STO
"something" 's3' STO
≫ ≫
===Testing if a string variable is empty===
2 methods:
IF s2 "" == THEN "Empty" END
IF s2 SIZE NOT THEN "Empty" END
===Testing if a string variable is not empty===
2 methods:
IF s3 "" ≠ THEN "Not empty" END
IF s3 SIZE THEN "Not empty" END
 
=={{header|Ruby}}==
 
Create an empty string
<langsyntaxhighlight lang="ruby">s = ""
s = String.new
s = "any string"; s.clear</langsyntaxhighlight>
 
These expressions all evaluate to true to determine emptiness:
<langsyntaxhighlight lang="ruby">s == ""
s.eql?("")
s.empty?
Line 1,321 ⟶ 2,969:
 
# also silly things like
s.each_char.to_a.empty?</langsyntaxhighlight>
 
Non-empty expressions, in addition to simply negating the above expressions:
<langsyntaxhighlight lang="ruby">s != ""
s.length > 0
s[/./m]</langsyntaxhighlight>
 
Note that we can '''not''' do the following, because the empty string is equivalent to true in Ruby ([[Boolean values#Ruby]]):
<langsyntaxhighlight lang="ruby">if s then puts "not empty" end # This code is wrong!</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">var$ = ""
' --------------
'empty string
Line 1,342 ⟶ 2,990:
' -------------
if var$<>"" then print "String Not empty."
if len(var$)>0 then print "String Not empty."</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">let s = "";
println!("is empty: {}", s.is_empty());
let t = "x";
println!("is empty: {}", t.is_empty());
let a = String::new();
println!("is empty: {}", a.is_empty());
let b = "x".to_string();
println!("is empty: {}", b.is_empty());
println!("is not empty: {}", !b.is_empty());</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">// assign empty string to a variable
val s=""
// check that string is empty
Line 1,354 ⟶ 3,013:
s.nonEmpty // false
s!="" // false
s.size>0 // false</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define empty-string "")
(define (string-null? s) (string=? "" s))
(define (string-not-null? s) (string<? "" s))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7"># assign empty string to a variable
s := ""
 
Line 1,369 ⟶ 3,028:
 
# check that string is not empty
s <> ""</langsyntaxhighlight>
 
=={{header|Self}}==
<langsyntaxhighlight lang="self">
"Put an empty string in a slot called 'str'"
str: ''.
Line 1,380 ⟶ 3,039:
"Check that string is not empty"
str isEmpty not.</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="self">
set emptyString to ""
 
put emptyString
 
put emptyString is empty
 
put emptyString is not empty
</syntaxhighlight>
{{out}}
<pre>
 
True
False</pre>
 
=={{header|Sidef}}==
Create an empty string:
<langsyntaxhighlight lang="ruby">var s = "";
var s = String.new;</langsyntaxhighlight>
 
These expressions all evaluate to true to determine emptiness:
<langsyntaxhighlight lang="ruby">s == "";
s.length == 0;
s.is_empty;
s ~~ /^\z/;
s ~~ /\A\z/;</langsyntaxhighlight>
 
Non-empty expressions, in addition to simply negating the above expressions:
<langsyntaxhighlight lang="ruby">s != "";
s.length > 0;
s ~~ /./s;
s !~ /^\z/;</langsyntaxhighlight>
 
=={{header|Slope}}==
<syntaxhighlight lang="slope">
(define test-string-1 "")
(define test-string-2 "Not empty")
 
(define empty-string? (lambda (x)
(and (string? x) (zero? (length x)))))
 
(empty-string? test-string-1) ; #t
(empty-string? test-string-2) ; #f
</syntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">"Assign empty string to a variable"
<lang smalltalk>
str := ''.
"Assign empty string to a variable"
str := ''.
 
"Check that string is empty"
str isEmpty.
 
"Check that string is not empty"
str isEmpty not.
"alternatives:"
</lang>
str notEmpty
str size = 0
str = ''</syntaxhighlight>
Notice that assignment is ":=" whereas equality check is "=".
 
=={{header|SNOBOL4}}==
An assignment statement with nothing to the right of the <tt>=</tt> operator assigns the empty string (or, as it is more commonly called in SNOBOL, the null string).
<langsyntaxhighlight lang="snobol4">* ASSIGN THE NULL STRING TO X
X =
* CHECK THAT X IS INDEED NULL
Line 1,421 ⟶ 3,111:
YES OUTPUT = 'NULL'
END
</syntaxhighlight>
</lang>
{{out}}
<pre>NULL</pre>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">(* Assign empty string to a variable *)
val s = ""
(* Check that a string is empty*)
s = ""
(* Check that a string is nonempty *)
s <> ""</langsyntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">scalar s=""
 
display s==""
 
* Alternatively, check the length
display length(s)==0</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var s = ""
if s.isEmpty { // alternately, s == ""
println("s is empty")
} else {
println("s is not empty")
}</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="tcl">set s ""
if {$s eq ""} {puts "s contains an empty string"}
if {$s ne ""} {puts "s contains a non-empty string"}</langsyntaxhighlight>
There are other ways to check for emptiness and non-emptiness too (though the above are favored for reasons of simplicity, clarity and speed):
<langsyntaxhighlight 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"}</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Line 1,460 ⟶ 3,158:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
s=""
IF (s=="") PRINT "s is an empty string"
IF (s!="") PRINT "s is a non-empty string"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,475 ⟶ 3,173:
====Pattern Matching====
 
<langsyntaxhighlight lang="txr">@(bind a "")</langsyntaxhighlight>
 
If <code>a</code> is unbound, a binding is created, containing the empty string.
Line 1,483 ⟶ 3,181:
====TXR Lisp====
 
<langsyntaxhighlight lang="txrlisp">(defvarl a "")
 
(if (equal a "")
Line 1,491 ⟶ 3,189:
 
(if (zerop (length a))
(format t "guess what?\n"))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="bash"># assign an empty string to a variable
s=""
 
Line 1,507 ⟶ 3,205:
# 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</langsyntaxhighlight>
 
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 <tt>[ $s = "" ]</tt>, then after variable substitition, the shell will try to evaluate <tt>[ = "" ]</tt> which is a syntax error.
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl string s
set s ""
 
Line 1,519 ⟶ 3,217:
else
out "not empty" endl console
end if</langsyntaxhighlight>
 
=={{header|VAX Assembly}}==
 
<syntaxhighlight lang="vax assembly">desc: .ascid "not empty" ;descriptor (len+addr) and text
.entry empty, ^m<>
tstw desc ;check length field
beql is_empty
;... not empty
clrw desc ;set length to zero -> empty
is_empty:
;... empty
ret
.end empty</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
dim s as string
 
' assign an empty string to a variable (six bytes):
s = ""
' assign null string pointer to a variable (zero bytes, according to RubberduckVBA):
s = vbNullString
' if your VBA code interacts with non-VBA code, this difference may become significant!
 
' test if a string is empty:
Line 1,537 ⟶ 3,251:
'or:
if Len(s) > 0 then Debug.Print "not empty."
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
See [[Empty_string#VBA|VBA]]
 
=={{header|Visual Basic}}==
See [[Empty_string#VBA|VBA]]
 
=={{header|Visual Basic .NET}}==
'''Compiler:''' Roslyn Visual Basic (language version >= 14, e.g. with Visual Studio 2015)
 
===In brief===
<syntaxhighlight lang="vbnet">Dim s As String
 
' Assign empty string:
s = ""
' or
s = String.Empty
 
' Check for empty string only (false if s is null):
If s IsNot Nothing AndAlso s.Length = 0 Then
End If
 
' Check for null or empty (more idiomatic in .NET):
If String.IsNullOrEmpty(s) Then
End If</syntaxhighlight>
 
===In depth===
Note: implementation information provided in comments was obtained reflecting .NET libraries and viewing the .NET Core reference source and may not be correct or remain relevant as time passes.
 
In .NET Core, functions defined in <code>Microsoft.VisualBasic</code> are only available for .NET Core 3.0 and above.
 
<syntaxhighlight lang="vbnet">Option Strict On
 
Module Program
Sub Main()
' Equality is somewhat convoluted in .NET, and VB doesn't help by adding legacy means of comparison.
' The methods above are the author's recommendation for each case.
' Some also return true if the string is Nothing/null; this is noted in the description for those that
' do.
 
' s is initialized to Nothing. It is a variable of the System.String type that is a null reference and is not
' the empty string.
Dim s As String = Nothing
 
' Alias Console.WriteLine(Boolean) with a shorter name to make the demonstration code less verbose.
Dim P As Action(Of Boolean) = AddressOf Console.WriteLine
 
' Assign the empty string literal to s.
s = ""
 
'' Assign String.Empty to s.
s = String.Empty
 
' The empty string literal is the same object reference as String.Empty because of string interning, meaning the
' behavior of the two is identical.
' From this point on, "" will be used instead of String.Empty for brevity.
 
'#Is operator
' The Is operator tests for reference equality. However, which strings are interned is a CLR implementation
' detail and may be unreliable when comparing non-empty strings. The equivalent in C# would be (object)s == "".
' Note that there is no such operator as Object.op_Equality(Object, Object): the use of the == operator for
' types of type Object is a C# language feature.
P(s Is "")
 
'#Object.ReferenceEquals(Object, Object)
' The previous line is semantically to the following, though it does not involve a method call.
P(Object.ReferenceEquals(s, ""))
 
'#= Operator
'True for Nothing.
' The VB.NET compiler does not use the System.String implementation of the equality operator. Instead, it emits
' a call to a method in the Visual Basic runtime, Operators.CompareString, which checks for reference equality
' before calling System.String.CompareOrdinal(String, String), which checks again for reference equality before
' comparing character-by-character.
P(s = "")
 
'#Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean)
'True for Nothing.
' Equivalent to the above line, though methods in the CompilerServices namespace are not meant for use by
' regular code.
' The third argument indicates whether to use a textual comparison (e.g. ignore case and diacritics).
P(0 = CompilerServices.Operators.CompareString(s, "", False))
 
'#Microsoft.VisualBasic.Strings.StrComp(String, String, [CompareMethod])
'True for Nothing.
' A wrapper around CompareString that is intended for use.
P(0 = StrComp(s, ""))
 
'#String.op_Equality(String, String)
' It is possible to directly call the equality operator of System.String, which is implemented as a call to
' String.Equals(String).
P(String.op_Equality(s, ""))
 
'#String.Equals(String, String)
' Call the static method defined on the String type.
' first calls Object.ReferenceEquals and then, after verifying that both are strings of the same length,
' compares the strings character-by-character.
P(String.Equals(s, ""))
 
'#Object.Equals(Object, Object)
' First checks for reference equality and whether one or both of the arguments is Nothing. It then invokes the
' instance Equals method of the left parameter.
P(Object.Equals(s, ""))
 
'#String.Equals(String)
' The method is called with the string literal as the receiver because a NullReferenceException is thrown if s
' is Nothing.
P("".Equals(s))
 
'#Microsoft.VisualBasic.Strings.Len(String)
'True for Nothing.
' Check the length using Microsoft.VisualBasic.Strings.Len(String). This method returns s?.Length (see below).
P(0 = Len(s))
 
'#String.Length
' Check the Length property. The ?. (null-conditional) operator is used to avoid NullReferenceException. The Equals
' call above can also be done this way.
' A method call must be added because the equality operator propagates Nothing/null (that is, the result of the
' expression is Nullable(Of Boolean)). This has the side effect of making it behave "correctly" for null.
P((s?.Length = 0).GetValueOrDefault())
 
' The If statement automatically unwraps nullable Booleans, however.
If s?.Length = 0 Then
End If
 
'#String.Length
' A more traditional version of the null-conditional using a guard clause.
' Both the null-conditional and this are noticeably (~4 times) faster than "".Equals(s). In general, it appears that
' for empty strings, using the length is faster than using an equality comparison.
P(s IsNot Nothing AndAlso s.Length = 0)
 
'#String.IsNullOrEmpty(String)
'True for Nothing
' A static method of System.String that returns true if the string is Nothing or its length is zero.
P(String.IsNullOrEmpty(s))
 
'#System.Collections.Generic.EqualityComparer(Of String).Default.Equals(String, String)
' The EqualityComparer(Of T) class provides default implementations when an IEqualityComparer(Of T) is required.
' The implementation for String calls String.Equals(String).
P(EqualityComparer(Of String).Default.Equals(s, ""))
 
Console.WriteLine()
 
' Each of the methods described above, except testing for a non-empty string.
P(s IsNot "")
P(Not Object.ReferenceEquals(s, ""))
P(s <> "")
P(0 <> CompilerServices.Operators.CompareString(s, "", False))
P(0 <> StrComp(s, ""))
P(String.op_Inequality(s, ""))
P(Not String.Equals(s, ""))
P(Not Object.Equals(s, ""))
P(Not "".Equals(s))
P(Len(s) <> 0)
P((s?.Length <> 0).GetValueOrDefault())
P(s Is Nothing OrElse s.Length <> 0)
P(Not String.IsNullOrEmpty(s))
P(Not EqualityComparer(Of String).Default.Equals(s, ""))
End Sub
End Module</syntaxhighlight>
 
{{out}}
<pre>True
True
True
True
True
True
True
True
True
True
True
True
True
True
 
False
False
False
False
False
False
False
False
False
False
False
False
False
False</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">// define and initialize an empty string
mut s := ""
 
// assign an empty string to a variable
s = ""
 
// check that a string is empty, any of:
s == ""
s.len() == 0
 
// check that a string is not empty, any of:
s != ""
s.len() != 0 // or > 0</syntaxhighlight>
::<syntaxhighlight lang="vlang">fn test(s string) {
if s.len() == 0 {
println("empty")
} else {
println("not empty")
}
}
 
fn main() {
// assign an empty string to a variable.
str1 := ""
str2 := " "
// check if a string is empty.
test(str1) // prt empty
// check that a string is not empty.
test(str2) // prt not empty
}</syntaxhighlight>
 
=={{header|Wee Basic}}==
<syntaxhighlight lang="wee basic">let string$=""
if string$=""
print 1 "The string is empty."
elseif string$<>""
print 1 "The string is not empty."
endif
end</syntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var isEmpty = Fn.new { |s| s == "" }
 
var s = ""
var t = "0"
System.print("'s' is empty? %(isEmpty.call(s))")
System.print("'t' is empty? %(isEmpty.call(t))")</syntaxhighlight>
 
{{out}}
<pre>
's' is empty? true
't' is empty? false
</pre>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<syntaxhighlight lang="asm">
option casemap:none
 
printf proto :qword, :VARARG
exit proto :dword
 
.data
e_str db 1 dup (0)
 
.code
main proc
xor rcx, rcx
lea rax, e_str
cmp byte ptr [rax+rcx],0 ;; Is e_str[0] equal to 0?
je _isempty ;; Yes so goto isEmpty
jne _notempty ;; No, got notEmpty
jmp _exit ;; Neither condition is met, so exit.
 
_isempty:
invoke printf, CSTR("e_str is empty",10)
lea rax, e_str
mov byte ptr [rax+0], 's' ;; Copy a char into e_str[0]
jmp main ;; Test again..
 
_notempty:
invoke printf, CSTR("e_str is NOT empty",10)
;; Fall though to exit here..
_exit:
xor rsi, rsi
call exit
ret
main endp
end
</syntaxhighlight>
{{out}}
<pre>
e_str is empty
e_str is NOT empty
</pre>
=={{header|XLISP}}==
<code>STRING-NULL?</code> returns true if its argument is a string of length zero. In a REPL:
<syntaxhighlight lang="scheme">[1] (define my-empty-string "") ;; assign an empty string to a variable
 
MY-EMPTY-STRING
[2] (string-null? my-empty-string)
 
#T
[3] (string-null? "A non-empty string")
 
()</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Text=12;
string 0; \use zero-terminated convention, instead of MSb set
char S;
Line 1,549 ⟶ 3,562:
if S(0) # 0 then Text(0, "not empty
");
]</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|6502 Assembly}}
An empty string is just a null terminator with no text in front.
<syntaxhighlight lang="z80">EmptyString:
byte 0</syntaxhighlight>
 
Checking if a string is empty is simple, just count the number of characters before you reach the terminator. If that count equals zero, the string is empty. Otherwise, the string is not empty.
 
<syntaxhighlight lang="z80">ld hl,MyString
 
GetStringLength:
ld b,0 ;zero the length counter
loop_getStringLength:
ld a,(hl)
or a ;compare A to zero
ret z ;exit if zero
 
inc hl ;next char
inc b ;add 1 to length counter
jr loop_getStringLength
 
ld a,b ;load B into A
or a ;compare A to zero (effectively comparing B to zero)
jr z,StringIsEmpty
;your code for what happens when MyString is not empty goes here.</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">s:=""; // or s:=String, String is the object ""
s.toBool() //-->False
if (s) println("not empty")</langsyntaxhighlight>
 
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">var string
string = ""
if eq string ""
print "The string is empty."
else
print "The string is not empty."
endif</syntaxhighlight>
For importing:
 
¶0¶var string¶0¶string = ""¶0¶if eq string ""¶1¶print "The string is empty."¶0¶else¶1¶print "The string is not empty."¶0¶endif
 
=={{header|ZX Spectrum Basic}}==
:''See [[#BASIC|BASIC]]''
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
// default is [:0]const u8, which is a 0-terminated string with len field
const str = "";
if (str.len == 0) {
std.debug.print("string empty\n", .{});
}
if (str.len != 0) {
std.debug.print("string not empty\n", .{});
}
}</syntaxhighlight>
 
{{omit from|GUISS}}
990

edits