Empty string: Difference between revisions
Content deleted Content added
m →{{header|Phix}}: marked p2js compatible |
No edit summary |
||
(49 intermediate revisions by 30 users not shown) | |||
Line 16:
=={{header|11l}}==
<
I s.empty
print(‘String s is empty.’)
I !s.empty
print(‘String s is not empty.’)</
=={{Header|4ME}}==
===4ME v1===
Since only the v1 of 4ME suports the operators =, > and <. It is imposible to check if the string is empty or not in 4ME v1.1
add{}
is
=
=={{header|6502 Assembly}}==
An empty string is just a null terminator with no text in front.
<
byte 0</
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.
<
sta $00
lda #>EmptyString
Line 44 ⟶ 50:
cpy #0
beq StringIsEmpty ;if this branch is taken, the string is empty
;otherwise, the string is not empty</
=={{header|68000 Assembly}}==
{{trans|6502 Assembly}}
An empty string is just a null terminator with no text in front.
<
DC.B 0
EVEN</
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.
<
getStringLength:
Line 66 ⟶ 72:
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.</
=={{header|8th}}==
Assign an empty string to a variable:
<
Check that the string is empty:
<
The check for a non-empty string is the same, but with "not" after the n:=
Line 81 ⟶ 87:
Declare an empty string at address <code>str</code>:
<
Check if a string stored at <code>x0</code> is empty:
<
ldrb w5, [x0]
cmp x5, #0</
Full program demo:
Line 93 ⟶ 99:
{{works with|aarch64-linux-gnu-as/qemu-aarch64}}
<
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
Line 148 ⟶ 154:
_exit:
mov x8, #SVC_EXIT
svc #0</
=={{header|ACL2}}==
To check if a string is empty:
<
=={{header|Action!}}==
<
PrintF("'%S' is empty? ",s)
IF s(0)=0 THEN
Line 172 ⟶ 178:
CheckIsEmpty(str1)
CheckIsEmpty(str2)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Empty_string.png Screenshot from Atari 8-bit computer]
Line 182 ⟶ 188:
=={{header|Ada}}==
<
function Is_Empty(S: String) return Boolean is
Line 196 ⟶ 202:
raise Program_Error with "something went wrong very very badly!!!";
end if;
end Empty_String;</
=={{header|Aime}}==
<
s = "";
if (length(s) == 0) {
Line 206 ⟶ 212:
if (length(s) != 0) {
....
}</
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
STRING s := "";
Line 221 ⟶ 227:
# 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</
=={{header|Apex}}==
<syntaxhighlight lang="apex">
String.isBlank(record.txt_Field__c);
--Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
</syntaxhighlight>
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝⍝ Assign empty string to A
A ← ''
Line 237 ⟶ 243:
~0 = ⍴∊ A
0
</syntaxhighlight>
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
-- assign empty string to str
set str to ""
Line 271 ⟶ 277:
-- str is not empty
end if
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 361 ⟶ 367:
</syntaxhighlight>
=={{header|Arturo}}==
<
if empty? s -> print "the string is empty"
Line 373 ⟶ 379:
if not? empty? s -> print "the string is not empty"
if 0 < size s -> print "no, the string is not empty"</
{{out}}
Line 381 ⟶ 387:
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.
<
; Assign an empty string:
var =
Line 404 ⟶ 437:
; Check that a string is not empty
If (var != "")
Msgbox the var is not empty</
=={{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.
<
Assert: emptyStringVar = "";
Assert: emptyStringVar = <>;
Assert: emptyStringVar is empty;
Assert: |emptyStringVar| = 0;</
Checking that a string is _not_ empty generally isn't any more interesting, just a logical negation of the above tests.
<
Assert: nonemptyStringVar ≠ "";
Assert: nonemptyStringVar ≠ <>;
Assert: ¬nonemptyStringVar is empty;
Assert: |nonemptyStringVar| > 0;</
The library also defines a type _nonempty string_, which can be leveraged for a type-membership check.
<syntaxhighlight lang
=={{header|AWK}}==
<
BEGIN {
# Demonstrate how to assign an empty string to a variable.
Line 443 ⟶ 476:
print "Is b empty ?",length(b)==0;
print "Is b not empty ?",length(b)!=0;
}</
{{out}}
<pre>$ awk -f R/tmp/string.awk
Line 457 ⟶ 490:
=={{header|Axe}}==
<
!If length(Str1)
Disp "EMPTY",i
Else
Disp "NOT EMPTY",i
End</
=={{header|BASIC}}==
<
20 IF A$="" THEN PRINT "THE STRING IS EMPTY"
30 IF A$<>"" THEN PRINT "THE STRING IS NOT EMPTY"
40 END</
==={{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.
<
40 IF LEN (A$) = 0 THEN PRINT "THE STRING IS EMPTY"
50 IF LEN (A$) THEN PRINT "THE STRING IS NOT EMPTY"</
==={{header|BaCon}}===
The literal empty string in BaCon is <tt>""</tt>.
<
a$ = ""
IF a$ = "" THEN PRINT "Empty string"
IF a$ != "" THEN PRINT "Non empty string"</
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}}===
<
20 IF A$="" THEN PRINT "The string is empty."
30 IF A$<>"" THEN PRINT "The string is not empty."</
==={{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}}===
<
If a$ = "" Then Print "Empty String"
If a$ <> "" Then Print a$ 'String is not empty, so print its contents.</
==={{header|
<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|SmallBASIC}}===
empty(s) returns true if s is empty.
<syntaxhighlight lang="qbasic">
s1 = ""
s2 = "abc"
print empty(s1)
print empty(s2)
</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 514 ⟶ 670:
::Alternatively,
if %var%@ neq @ echo Var is not a blank string.
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
var$ = ""
Line 525 ⟶ 681:
REM Check that a string is not empty:
IF var$ <> "" THEN PRINT "String is not empty"
</syntaxhighlight>
=={{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}}==
Line 532 ⟶ 711:
To check emptiness, we can check the length of the array using <code>≠</code> (or shape with <code>≢</code>).
<
•Show 0 = ≠ ""
•Show 0 ≠ ≠ ""
•Show "" ≡ ⟨⟩</
⟨⟩
1
0
1</
=={{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.
<
& (b=)
& abra:?c
Line 552 ⟶ 731:
& !d:~ { neither is d an empty string }
)
</syntaxhighlight>
=={{header|Burlesque}}==
Line 558 ⟶ 737:
Empty string is <tt>""</tt> and checking for empty strings (or empty lists) can be done with the <tt>nu</tt> command.
<
blsq ) ""
""
Line 565 ⟶ 744:
blsq ) "a"nu
0
</syntaxhighlight>
=={{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.
<
/* ... */
Line 588 ⟶ 767:
/* or compare to a known empty string, same thing. "== 0" means strings are equal */
if (strcmp(str, "") == 0) { ... }
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
class Program {
Line 599 ⟶ 778:
if (!string.IsNullOrEmpty(example)) { }
}
}</
===In depth===
Line 606 ⟶ 785:
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.
<
using System.Collections.Generic;
Line 718 ⟶ 897:
P(!EqualityComparer<string>.Default.Equals(s, ""));
}
}</
=={{header|C++}}==
<
// ...
Line 759 ⟶ 938:
// create empty string as default parameter
void func( std::string& s = {} ); // {} generated default std:string instance
</syntaxhighlight>
=={{header|Caché ObjectScript}}==
<
; Demonstrate how to assign an empty string to a variable.
set x = ""
Line 776 ⟶ 955:
write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."")
quit</
{{out}}SAMPLES>do EMPTYSTR^ROSETTA
Line 787 ⟶ 966:
=={{header|Clojure}}==
<
(def x "") ;x is "globally" declared to be the empty string
(let [x ""]
Line 794 ⟶ 973:
(= x "") ;true if x is the empty string
(not= x "") ;true if x is not the empty string
</syntaxhighlight>
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. EMPTYSTR.
Line 821 ⟶ 1,000:
STOP RUN.
</syntaxhighlight>
=={{header|CoffeeScript}}==
Empty strings are mostly straightforward in CoffeeScript, but there's one gotcha.
<
isEmptyString = (s) ->
# Returns true iff s is an empty string.
Line 839 ⟶ 1,018:
console.log (s = '') == "" # true
console.log new String() == '' # false, due to underlying JavaScript's distinction between objects and primitives
</syntaxhighlight>
=={{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.
<
(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
;; (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
<
MODULE EmptyString;
IMPORT StdLog;
Line 872 ⟶ 1,056:
END Do;
END EmptyString.
</syntaxhighlight>
Execute: ^Q EmptyString.Do<br/>
{{out}}
Line 885 ⟶ 1,069:
=={{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.
<
bool isEmptyNotNull(in string s) pure nothrow @safe {
Line 911 ⟶ 1,095:
assert(s1.empty);
assert(s2.isEmptyNotNull());
}</
=={{header|Dart}}==
<
var empty = '';
Line 925 ⟶ 1,109:
print('it is not empty');
}
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 947 ⟶ 1,131:
s := 'abc';
Writeln(StringIsEmpty(s)); // False
end.</
=={{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}}==
<
s := ''; // assign an empty string (can also use "")
Line 960 ⟶ 1,211:
if s <> '' then
PrintLn('not empty');</
=={{header|Dyalect}}==
Line 966 ⟶ 1,217:
Demonstrate how to assign an empty string to a variable:
<
Demonstrate how to check that a string is empty:
<
Demonstrate how to check that a string is not empty:
<
=={{header|Déjà Vu}}==
Like in Python, empty strings are falsy, non-empty strings are truthy.
<
if not e:
Line 988 ⟶ 1,235:
if e:
!print "not an empty string"</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">a$ = ""
if a$ = ""
print "empty"
Line 998 ⟶ 1,245:
if a$ <> ""
print "no empty"
.</
=={{header|ed}}==
ed has no concept of string, only lines. Still, one can empty (or even delete) a line. Checking for emptiness requires conditional matching with <tt>g</tt> and <tt>v</tt>.
<syntaxhighlight lang="sed">
# Empty the string (line)
s/.*//
# Check for emptiness
g/.+/s//Not empty/
v/Not empty/s//Empty</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x:
<
public program()
Line 1,013 ⟶ 1,271:
if (s.isNonempty())
{ console.printLine("'", s, "' is not empty") }
}</
{{out}}
<pre>
Line 1,021 ⟶ 1,279:
=={{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)).
<
empty_string = ""
not_empty_string = "a"
Line 1,038 ⟶ 1,296:
byte_size(not_empty_string) == 0
# => false
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<
(if (= 0 (length str))
(message "string is empty"))
(if (/= 0 (length str))
(message "string is not empty"))</
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}}==
<
1> S = "". % erlang strings are actually lists, so the empty string is the same as the empty list [].
[]
Line 1,060 ⟶ 1,346:
4> case "aoeu" of [] -> empty; [H|T] -> not_empty end.
not_empty
</syntaxhighlight>
=={{header|Euphoria}}==
<
-- assign an empty string
Line 1,077 ⟶ 1,363:
if length(s) then
-- string is not empty
end if</
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
Line 1,087 ⟶ 1,373:
printfn "Is empty %A: %A" emptyString (emptyString = String.Empty)
printfn "Is not empty %A: %A" emptyString (emptyString <> String.Empty)
0</
{{out}}
<pre>Is empty "": true
Line 1,096 ⟶ 1,382:
It's idiomatic in Factor to prefer using the stack over variable bindings.
<
{{out}}
<pre>
Line 1,104 ⟶ 1,390:
However, Factor provides lexical variables:
<
[let
"" :> empty-string
empty-string empty? .
empty-string empty? not .
]</
{{out}}
<pre>
Line 1,120 ⟶ 1,406:
Fantom uses "" to represent an empty string, and provides the isEmpty method to check if a string is empty.
<
a := "" // assign an empty string to 'a'
a.isEmpty // method on sys::Str to check if string is empty
Line 1,126 ⟶ 1,412:
a == "" // alternate check for an empty string
!a.isEmpty // check that a string is not empty
</syntaxhighlight>
=={{header|Forth}}==
Strings are represented as an addr-len pair on the stack. An empty string has len 0.
<
\ 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 1,137 ⟶ 1,423:
: filled? ( c-addr u -- ? ) empty? 0= ;
: ="" ( c-addr u -- ) drop 0 ; \ It's OK to copy syntax from other languages
</syntaxhighlight>
Forth Console Test (True= -1, False=0)
Line 1,153 ⟶ 1,439:
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.
<
CHARACTER*(*) T !This form allows for any size.
IF (LEN(T).LE.0) WRITE(6,*) "Empty!"
Line 1,163 ⟶ 1,449:
TEXT = "" !Fills the entire variable with space characters.
CALL TASTE(TEXT) !Passes all 24 of them. Result is Not empty!
END</
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 1,172 ⟶ 1,458:
=={{header|Free Pascal}}==
Assigning an empty string:
<
Checking for an empty string:
<
length(s) = 0</
Checking for a non-empty string:
<
length(s) > 0
longBool(length(s))</
The <code>sysUtils</code> unit defines the constants <code>emptyStr</code> and <code>emptyWideStr</code>, which can be used in place of <code>''</code>.
=={{header|FreeBASIC}}==
<
Sub IsEmpty(s As String)
Line 1,199 ⟶ 1,485:
Dim u As String = "not empty"
IsEmpty(u)
Sleep</
{{out}}
Line 1,209 ⟶ 1,495:
=={{header|Frink}}==
<
if a == ""
println["empty"]
if a != ""
println["Not empty"]</
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"Empty string", (0,0,480,270)
CFStringRef s
s = @""
if
if ( fn StringLength( s
if ( len(s) == 0 ) then print @"
print
s = @"Hello"
if ( fn StringIsEqual( s, @"" ) == NO ) then print @"string not empty"
if ( fn StringLength( s ) != 0 ) then print @"string not empty"
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]'''
<
Dim sString As String[] = ["", "Hello", "world", "", "Today", "Tomorrow", "", "", "End!"]
Dim sTemp As String
Line 1,251 ⟶ 1,537:
Next
End</
Output:
<pre>
Line 1,269 ⟶ 1,555:
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.
<
var s string
s2 := ""
Line 1,282 ⟶ 1,568:
// check that a string is not empty, any of:
s != ""
len(s) != 0 // or > 0</
::<
import (
Line 1,305 ⟶ 1,591:
// check that a string is not empty.
test(str2) // prt not empty
}</
=={{header|Groovy}}==
<
assert s.empty
s = '1 is the loneliest number'
assert !s.empty</
=={{header|GW-BASIC}}==
<
20 S2$ = "" 'explicitly defined empty string
30 S3$ = "Foo bar baz"
Line 1,323 ⟶ 1,609:
70 END
200 IF LEN(S$)=0 THEN PRINT "Empty string" ELSE PRINT "Non-empty string"
210 RETURN</
=={{header|Harbour}}==
<
// 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).
Line 1,333 ⟶ 1,619:
IF ! Empty( cString ) // --> FALSE
? cString
ENDIF</
=={{header|Haskell}}==
<
-- In Haskell strings are just lists (of characters), so we can use the function
Line 1,345 ⟶ 1,631:
let s = ""
when (null s) (putStrLn "Empty.")
when (not $ null s) (putStrLn "Not empty.")</
=={{header|HolyC}}==
<
U8 *str = StrNew("");
/* or */
Line 1,359 ⟶ 1,645:
/* to test if string is not empty */
if (StrLen(str)) { ... }</
=={{header|i}}==
<
s = ""
Line 1,375 ⟶ 1,661:
end
}
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon can produce empty strings in several ways:
<
s := string('A'--'A') # ... converted from cset difference
s := char(0)[0:0] # ... by slicing
Line 1,394 ⟶ 1,680:
s := &null # NOT a null string, null type
/s # test for null type
\s # test for non-null type </
=={{header|J}}==
<
0=#variable
1
0<#variable
0</
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.
<
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");
}</
=={{header|JavaScript}}==
Create an empty String
<
var s = new String();</
Boolean expressions representing emptiness
<
s.length == 0
!s
!Boolean(s)</
Non-emptiness
<
s != ""
s.length != 0
s.length > 0
Boolean(s)</
=={{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.
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:<syntaxhighlight lang="jq">s == ""
# or:
s|length == 0</
# or:
s.length != 0 # etc.</
=={{header|Jsish}}==
<
var em1 = '';
var em2 = new String();
Line 1,495 ⟶ 1,796:
(em1 === em2) ==> true
=!EXPECTEND!=
*/</
{{out}}
Line 1,522 ⟶ 1,823:
=={{header|Julia}}==
<syntaxhighlight lang="julia">
blank = ""
nonblank = "!"
Line 1,534 ⟶ 1,835:
println("That nonblank is empty is ", isempty(nonblank))
println("That nonblank is not empty is ", !isempty(nonblank))
</syntaxhighlight>
{{out}}
Line 1,550 ⟶ 1,851:
{{trans|J}}
<
0=#variable
1
0<#variable
0</
=={{header|Kotlin}}==
<
val s = ""
println(s.isEmpty()) // true
Line 1,564 ⟶ 1,865:
println(s.none()) // true
println(s.any()) // false
}</
=={{header|LabVIEW}}==
Line 1,571 ⟶ 1,872:
=={{header|Lambdatalk}}==
In Lambdatalk primitives working on sequences of words begin with "S."
<
'{def emptyString }
-> emptyString
Line 1,583 ⟶ 1,884:
'{= {S.length {emptyString}} 0}
-> true
</syntaxhighlight>
=={{
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}}==
<
local(str = string)
local(str = '')
Line 1,609 ⟶ 1,930:
local(str = 'Hello, World!')
#str->size > 0 // true
#str->size // true</
=={{header|Latitude}}==
Assigning the empty string.
<
s := String clone.</
Checking whether a string is empty.
<
s empty?.
s length == 0.</
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.
Line 1,629 ⟶ 1,950:
{{trans|Erlang}}
<
> (set str "")
()
Line 1,654 ⟶ 1,975:
> (case "apple" ('() 'empty) ((cons head tail) 'not-empty))
not-empty
</syntaxhighlight>
=={{header|Lhogho}}==
Lhogho is a Logo compiler for Windows and Linux
<
print empty? :str ;prints 'true'
print not empty? :str ;prints 'false'
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'assign empty string to variable
a$ = ""
Line 1,673 ⟶ 1,994:
if a$<>"" then print "Not empty."
if len(a$)>0 then print "Not empty."
</syntaxhighlight>
=={{header|Lingo}}==
<
put str=EMPTY
-- 1
put str<>EMPTY
-- 0</
=={{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>
<
I HAS A string ITZ ""
Line 1,692 ⟶ 2,013:
OIC
KTHXBYE</
=={{header|Lua}}==
<syntaxhighlight lang="lua">
-- create an empty string 3 different ways
str = ""
Line 1,722 ⟶ 2,043:
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 {
\\
Line 1,820 ⟶ 2,141:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight 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>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
str=""; (*Create*)
str==="" (*test empty*)
str=!="" (*test not empty*)
</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
<
str = '';
% Demonstrate how to check that a string is empty.
Line 1,845 ⟶ 2,166:
% Demonstrate how to check that a string is not empty.
~isempty(str)
(length(str)>0)</
=={{header|Maxima}}==
<
/* check using string contents */
Line 1,856 ⟶ 2,177:
/* check using string length */
slength(s) = "";
slength(s) # "";</
=={{header|Mercury}}==
Line 1,862 ⟶ 2,183:
There's nothing special about empty strings in Mercury.
<
( if S = "" then ... else ... ), % checking if a string is empty
( if not S = "" then ... else ... ), % checking if a string is not empty</
=={{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>.
<
"" empty? puts!
"Rosetta Code" empty? puts!</
{{out}}
<pre>
Line 1,879 ⟶ 2,200:
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}}==
<
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</
=={{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}}==
<
if len(s)=0
Line 1,895 ⟶ 2,276:
else
println "s is not empty"
end</
=={{header|Nemerle}}==
Assign an empty string:
<
mutable fill_later = "";</
Check if a string is empty/not empty:
<
a_string.Length == 0; a_string.Length > 0;</
=={{header|NESL}}==
<
% To make sure it is empty, we can ask whether its length is equal to zero. %
#my_empty_string == 0;</
{{out}}
<pre>my_empty_string = "" : [char]
Line 1,917 ⟶ 2,298:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols binary
Line 1,938 ⟶ 2,319:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,948 ⟶ 2,329:
=={{header|Nim}}==
<
if x == "":
Line 1,959 ⟶ 2,340:
echo "empty"
if x.len > 0:
echo "not empty"</
=={{header|NS-HUBASIC}}==
<
20 IF S$<>"" THEN O$="NOT "
30 PRINT "THE STRING IS "O$"EMPTY."</
=={{header|Nyquist}}==
===Lisp Syntax===
<
(setf emptystring "") ;binds variable'emptystring' to the empty string ""
Line 1,982 ⟶ 2,363:
(when (and (stringp emptystring)(> (length emptystring) 0))
(print "Is a non-empty string")))
</syntaxhighlight>
===SAL Syntax===
<
define variable emptystring = "" ;binds variable'emptystring' to the empty string ""
Line 1,992 ⟶ 2,373:
else
print "is not empty string"
</syntaxhighlight>
===Audacity plug-in (LISP syntax)===
<
;nyquist plug-in
;version 4
Line 2,007 ⟶ 2,388:
"The string is empty."
"The string is not empty.")
</syntaxhighlight>
===Audacity plug-in (SAL syntax)===
<syntaxhighlight lang="nyquist">
;nyquist plug-in
;version 4
Line 2,024 ⟶ 2,405:
"The string is empty.",
"The string is not empty.")
</syntaxhighlight>
=={{header|oberon-2}}==
{{works with|oo2c version 2}}
<
MODULE EmptyString;
IMPORT Out;
Line 2,043 ⟶ 2,424:
Out.String("checking str[0] = 0X. Is Empty? ");Out.Bool(str[0] = 0X);Out.Ln;
END EmptyString.
</syntaxhighlight>
{{out}}
<pre>
Line 2,055 ⟶ 2,436:
=={{header|Objeck}}==
<
s := "";
if(s->IsEmpty()) {
Line 2,062 ⟶ 2,443:
"s is not empty"->PrintLine();
};
</syntaxhighlight>
=={{header|OCaml}}==
<
(s = "")
Line 2,074 ⟶ 2,455:
Printf.printf "s1 empty? %B\n" (is_string_empty s1);
Printf.printf "s2 empty? %B\n" (is_string_empty s2);
;;</
{{out}}
Line 2,086 ⟶ 2,467:
isEmpty can be used on all collections, not only strings.
<
"" isEmpty not</
=={{header|Ol}}==
<syntaxhighlight lang="ol">
; define the empty string
(define empty-string "")
Line 2,109 ⟶ 2,490:
(less? 0 (string-length the-string)))
(print "the-string is NOT empty))
</syntaxhighlight>
=={{header|ooRexx}}==
should work with each and every REXX interpreter/compiler.
<
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' </
{{out}}
<pre>v contains the empty string
Line 2,126 ⟶ 2,507:
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.
<
IF cc > '' THEN
Line 2,134 ⟶ 2,515:
ELSE /* IF cc = '' */
MESSAGE 'empty' VIEW-AS ALERT-BOX.
</syntaxhighlight>
=={{header|PARI/GP}}==
<
isEmpty(s)=s=="" \\ Alternately:
isEmpty(s)=#s==0
isNonempty(s)=s!="" \\ Alternatively:
isNonempty(s)=#s</
=={{header|Pascal}}==
''See also [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]]''
{{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, '') : True
length(s) = 0 : True
NE(s, '') : False
length(s) > 0 : False
!!! s = ' ' : True
trim(s) = '' : True
=={{header|Perl}}==
<
print "The string is empty";
}
if ($s ne "") { # Test for non empty string
print "The string is not empty";
}</
In Perl, an empty string is often used to represent a false value.
<
if ($s) { ... } # false
Line 2,168 ⟶ 2,581:
# but a string that converts to number 0 is not always false, though:
$s = "0 but true";
if ($s) { ... } # it's true! black magic!</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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>
Line 2,183 ⟶ 2,596:
<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>
<!--</
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Empty_string
by Galileo, 10/2022 #/
"" var s
s len if "String is NOT empty" else "String IS empty" endif print nl
" " "" == if "String IS empty" else "String is NOT empty" endif print
</syntaxhighlight>
{{out}}
<pre>String IS empty
String is NOT empty
=== Press any key to exit ===</pre>
=={{header|PHP}}==
<
$str = ''; // assign an empty string to a variable
Line 2,201 ⟶ 2,627:
if (strlen($str) == 0) { ... }
if (strlen($str) != 0) { ... }</
=={{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.
<
(off String)
(setq String "")
Line 2,218 ⟶ 2,656:
(and String ..)
(if String ..)
(when String ..)</
=={{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}}==
<
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>
=={{header|Plain English}}==
<
Start up.
Put "" into a string.
Line 2,234 ⟶ 2,686:
If the string is not blank, write "Not empty!" on the console.
Wait for the escape key.
Shut down.</
=={{header|PowerShell}}==
Assignment (the type identifier is optional):
<syntaxhighlight lang="powershell">
[string]$alpha = "abcdefghijklmnopqrstuvwxyz"
[string]$empty = ""
# or...
[string]$empty = [String]::Empty
</syntaxhighlight>
Tests:
<syntaxhighlight lang="powershell">
[String]::IsNullOrEmpty($alpha)
[String]::IsNullOrEmpty($empty)
</syntaxhighlight>
{{Out}}
<pre>
Line 2,257 ⟶ 2,709:
=={{header|Prolog}}==
{{works with|SWI-Prolog|7}}
<
is_empty_string(String) :- String == "".
not_empty_string(String) :- String \== "".
</syntaxhighlight>
=={{header|PureBasic}}==
In PureBasic we can just test a string for truth to determine if it has a value.
<
If a
ProcedureReturn "String is not empty, it contains '" + a + "'."
Line 2,281 ⟶ 2,733:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>String is empty, or null.
Line 2,290 ⟶ 2,742:
Any non-empty ''string'', including '0', is always treated as True in a boolean context.
<
s = ''
# or:
Line 2,317 ⟶ 2,769:
elif s is None:
return True
</syntaxhighlight>
=={{header|QB64}}==
<
If Len(s1) = 0 Then Print "Empty"
Line 2,328 ⟶ 2,780:
s3$ = "cat"
If Len(s3$) <> 0 Then Print "Not empty"
If s3$ <> "" Then Print "Still not empty"</
{{out}}
<pre>
Line 2,342 ⟶ 2,794:
Demonstrated as a dialogue in the Quackery REPL.
<
Enter "leave" to leave the shell.
Line 2,360 ⟶ 2,812:
...
Aloha.</
=={{header|Quite BASIC}}==
<
20 if s="" then let o=""
30 if s<>"" then let o="not "
40 print "The string is ";o;"empty."</
=={{header|R}}==
<
if (s == '') cat('Empty\n')
Line 2,377 ⟶ 2,829:
if (s != '') cat('Not empty\n')
#or
if (nchar(s) > 0) cat('Not empty\n')</
=={{header|Racket}}==
<
(define empty-string "")
(define (string-null? s) (string=? "" s))
(define (string-not-null? s) (string<? "" s))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say 'String is empty' unless $s;
say 'String is not empty' if $s;</
Unlike in Perl 5, only empty strings test as false - the string "0" tests as true now.
=={{header|Rascal}}==
<
if (s=="") print("string s is empty");
if (s!="") print("string s is not empty");
</syntaxhighlight>
Or the build-in operator:
<
if (isEmpty(s)) print("string s is empty");
if (isEmpty(s)) print("string s is not empty");</
=={{header|Red}}==
<
s: copy "" ;; assign empty string
?? s
Line 2,413 ⟶ 2,865:
s: "abc"
prin s unless empty? s [print " not empty"]
</syntaxhighlight>
{{out}}
<pre>s: ""
Line 2,423 ⟶ 2,875:
=={{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">
( by creating a variable )
"" keepString variable: foo
Line 2,429 ⟶ 2,881:
( by setting an existing variable 'foo' )
"" keepString !foo
</syntaxhighlight>
Checking that a string is empty. A string with a length of zero is assumed to be empty.
<syntaxhighlight lang="retro">
: emtpy? ( $-f ) getLength 0 = ;
"" empty? putn
"hello" empty? putn
</syntaxhighlight>
Check that a string is not empty.
<syntaxhighlight lang="retro">
: notEmpty? ( $-f ) getLength 0 > ;
"" notEmpty? putn
"hello" notEmpty? putn
</syntaxhighlight>
=={{header|REXX}}==
<
/*─────────────── 3 simple ways to assign an empty string to a variable.*/
Line 2,488 ⟶ 2,940:
if length(cod)\=0 then fish=cod /*a not-as-fast compare. */
/*────────────────────────── anyway, as they say: "choose your poison." */</
=={{header|Ring}}==
<
cStr = NULL # empty string
if cStr = NULL
Line 2,498 ⟶ 2,950:
see "cstr is not empty string!" + nl
ok
</syntaxhighlight>
=={{header|Robotic}}==
<
set "$string" to ""
if "$string.length" = 0 then "empty"
Line 2,510 ⟶ 2,962:
* "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
<
s = String.new
s = "any string"; s.clear</
These expressions all evaluate to true to determine emptiness:
<
s.eql?("")
s.empty?
Line 2,527 ⟶ 2,995:
# also silly things like
s.each_char.to_a.empty?</
Non-empty expressions, in addition to simply negating the above expressions:
<
s.length > 0
s[/./m]</
Note that we can '''not''' do the following, because the empty string is equivalent to true in Ruby ([[Boolean values#Ruby]]):
<
=={{header|Run BASIC}}==
<
' --------------
'empty string
Line 2,548 ⟶ 3,016:
' -------------
if var$<>"" then print "String Not empty."
if len(var$)>0 then print "String Not empty."</
=={{header|Rust}}==
<
println!("is empty: {}", s.is_empty());
let t = "x";
Line 2,559 ⟶ 3,027:
let b = "x".to_string();
println!("is empty: {}", b.is_empty());
println!("is not empty: {}", !b.is_empty());</
=={{header|Scala}}==
<
val s=""
// check that string is empty
Line 2,571 ⟶ 3,039:
s.nonEmpty // false
s!="" // false
s.size>0 // false</
=={{header|Scheme}}==
<
(define (string-null? s) (string=? "" s))
(define (string-not-null? s) (string<? "" s))</
=={{header|Seed7}}==
<
s := ""
Line 2,586 ⟶ 3,054:
# check that string is not empty
s <> ""</
=={{header|Self}}==
<
"Put an empty string in a slot called 'str'"
str: ''.
Line 2,597 ⟶ 3,065:
"Check that string is not empty"
str isEmpty not.</
=={{header|SenseTalk}}==
<
set emptyString to ""
Line 2,608 ⟶ 3,076:
put emptyString is not empty
</syntaxhighlight>
{{out}}
<pre>
Line 2,617 ⟶ 3,085:
=={{header|Sidef}}==
Create an empty string:
<
var s = String.new;</
These expressions all evaluate to true to determine emptiness:
<
s.length == 0;
s.is_empty;
s ~~ /^\z/;
s ~~ /\A\z/;</
Non-empty expressions, in addition to simply negating the above expressions:
<
s.length > 0;
s ~~ /./s;
s !~ /^\z/;</
=={{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}}==
<
str := ''.
Line 2,645 ⟶ 3,125:
str notEmpty
str size = 0
str = ''</
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).
<
X =
* CHECK THAT X IS INDEED NULL
Line 2,657 ⟶ 3,137:
YES OUTPUT = 'NULL'
END
</syntaxhighlight>
{{out}}
<pre>NULL</pre>
=={{header|Standard ML}}==
<
val s = ""
(* Check that a string is empty*)
s = ""
(* Check that a string is nonempty *)
s <> ""</
=={{header|Stata}}==
<
display s==""
* Alternatively, check the length
display length(s)==0</
=={{header|Swift}}==
<
if s.isEmpty { // alternately, s == ""
println("s is empty")
} else {
println("s is not empty")
}</
=={{header|Symstatic}}==
You can always use equality to check for the empty string.
<syntaxhighlight lang="symstatic">let eps := ""
assert(eps = "")
assert(eps /= "foo")
</syntaxhighlight>
=={{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.
<
if {$s eq ""} {puts "s contains an empty string"}
if {$s ne ""} {puts "s contains a non-empty string"}</
There are other ways to check for emptiness and non-emptiness too (though the above are favored for reasons of simplicity, clarity and speed):
<
if {[string length $s] == 0} {puts "is empty"}
if {[string compare $s ""] != 0} {puts "is non-empty"}</
=={{header|TorqueScript}}==
Line 2,704 ⟶ 3,192:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
s=""
IF (s=="") PRINT "s is an empty string"
IF (s!="") PRINT "s is a non-empty string"
</syntaxhighlight>
{{out}}
<pre>
Line 2,719 ⟶ 3,207:
====Pattern Matching====
<
If <code>a</code> is unbound, a binding is created, containing the empty string.
Line 2,727 ⟶ 3,215:
====TXR Lisp====
<
(if (equal a "")
Line 2,735 ⟶ 3,223:
(if (zerop (length a))
(format t "guess what?\n"))</
=={{header|UNIX Shell}}==
<
s=""
Line 2,751 ⟶ 3,239:
# 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</
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}}==
<
set s ""
Line 2,763 ⟶ 3,251:
else
out "not empty" endl console
end if</
=={{header|VAX Assembly}}==
<
.entry empty, ^m<>
tstw desc ;check length field
Line 2,776 ⟶ 3,264:
;... empty
ret
.end empty</
=={{header|VBA}}==
<syntaxhighlight lang="vb">
dim s as string
Line 2,797 ⟶ 3,285:
'or:
if Len(s) > 0 then Debug.Print "not empty."
</syntaxhighlight>
=={{header|VBScript}}==
Line 2,809 ⟶ 3,297:
===In brief===
<
' Assign empty string:
Line 2,822 ⟶ 3,310:
' Check for null or empty (more idiomatic in .NET):
If String.IsNullOrEmpty(s) Then
End If</
===In depth===
Line 2,829 ⟶ 3,317:
In .NET Core, functions defined in <code>Microsoft.VisualBasic</code> are only available for .NET Core 3.0 and above.
<
Module Program
Line 2,957 ⟶ 3,445:
P(Not EqualityComparer(Of String).Default.Equals(s, ""))
End Sub
End Module</
{{out}}
Line 2,989 ⟶ 3,477:
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}}==
<
if string$=""
print 1 "The string is empty."
Line 2,997 ⟶ 3,517:
print 1 "The string is not empty."
endif
end</
=={{header|Wren}}==
<
var s = ""
var t = "0"
System.print("'s' is empty? %(isEmpty.call(s))")
System.print("'t' is empty? %(isEmpty.call(t))")</
{{out}}
Line 3,015 ⟶ 3,535:
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<
option casemap:none
Line 3,048 ⟶ 3,568:
main endp
end
</syntaxhighlight>
{{out}}
<pre>
Line 3,056 ⟶ 3,576:
=={{header|XLISP}}==
<code>STRING-NULL?</code> returns true if its argument is a string of length zero. In a REPL:
<
MY-EMPTY-STRING
Line 3,064 ⟶ 3,584:
[3] (string-null? "A non-empty string")
()</
=={{header|XPL0}}==
<
string 0; \use zero-terminated convention, instead of MSb set
char S;
Line 3,076 ⟶ 3,596:
if S(0) # 0 then Text(0, "not empty
");
]</
=={{header|Z80 Assembly}}==
{{trans|6502 Assembly}}
An empty string is just a null terminator with no text in front.
<
byte 0</
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.
<
GetStringLength:
Line 3,102 ⟶ 3,622:
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.</
=={{header|zkl}}==
<
s.toBool() //-->False
if (s) println("not empty")</
=={{header|Zoomscript}}==
For typing:
<
string = ""
if eq string ""
Line 3,117 ⟶ 3,637:
else
print "The string is not empty."
endif</
For importing:
Line 3,124 ⟶ 3,644:
=={{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}}
|