Empty string: Difference between revisions

From Rosetta Code
Content added Content deleted
(+Java)
(→‎{{header|Perl 6}}: Add Perl 6 example)
Line 18: Line 18:
System.out.println("s is not empty");
System.out.println("s is not empty");
}</lang>
}</lang>
=={{header|Perl 6}}==
In Perl 6 we can't just test a string for truth to determine if it has a value. The string "0" will test as false even though it has a value. Instead we must test for length.

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

=={{header|Python}}==
=={{header|Python}}==
<lang python>s = ''
<lang python>s = ''

Revision as of 21:39, 4 July 2011

Empty string is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Some languages have syntax or semantics for dealing specifically with empty strings.

The task is to:

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

Java

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

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

}else{

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

}</lang>

Perl 6

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

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

Python

<lang python>s = if not s:

   print('String s is empty.')

if s:

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