Strip whitespace from a string/Top and tail

From Rosetta Code
Revision as of 13:13, 4 June 2011 by rosettacode>ShinTakezou (→‎{{header|QBasic}}: ++ perl (guru can do better))
Strip whitespace from a string/Top and tail 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.

The task is to demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results:

  • String with leading whitespace removed
  • String with trailing whitespace removed
  • String with both leading and trailing whitespace removed

For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation.

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>
  3. include <ctype.h>

char *rtrim(const char *s) {

 while( isspace(*s) ) ++s;
 return strdup(s);

}

char *ltrim(const char *s) {

 char *r = strdup(s);
 if (r != NULL)
 {
   char *fr = r + strlen(s) - 1;
   while( (isspace(*fr) || *fr == 0) && fr >= r) --fr;
   *++fr = 0;
 }
 return r;

}

char *trim(const char *s) {

 char *r = rtrim(s);
 char *f = ltrim(r);
 free(r);
 return f;

}

const char *a = " this is a string ";

int main() {

 char *b = rtrim(a);
 char *c = ltrim(a);
 char *d = trim(a);
 printf("'%s'\n'%s'\n'%s'\n", b, c, d);
 
 free(b);
 free(c);
 free(d);
 return 0;

}</lang>

J

Note: The quote verb is only used to enclose the resulting string in single quotes so the the beginning and end of the new string are visible. <lang j> require 'strings' NB. the strings library is automatically loaded in versions from J7 on

  quote dlb '  String with spaces   '    NB. delete leading blanks

'String with spaces '

  quote dtb '  String with spaces   '    NB. delete trailing blanks

' String with spaces'

  quote dltb '  String with spaces   '   NB. delete leading and trailing blanks

'String with spaces'</lang> In addition deb (delete extraneous blanks) will trim both leading and trailing blanks as well as replace consecutive spaces within the string with a single space. <lang j> quote deb ' String with spaces ' NB. delete extraneous blanks 'String with spaces'</lang> These existing definitions can be easily amended to include whitespace other than spaces if desired. <lang j>dlws=: }.~ (e.&(' ',TAB) i. 0:) NB. delete leading whitespace (spaces and tabs) dtws=: #~ ([: +./\. -.@:e.&(' ',TAB)) NB. delete trailing whitespace dltws=: #~ ([: (+./\ *. +./\.) -.@:e.&(' ',TAB)) NB. delete leading & trailing whitespace dews=: #~ (+. (1: |. (> </\)))@(-.@:e.&(' ',TAB)) NB. delete extraneous whitespace</lang>

Java

Left trim and right trim taken from here.

Character.isWhitespace() returns true if the character given is one of the following Unicode characters: '\u00A0', '\u2007', '\u202F', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u001C', '\u001D', '\u001E', or '\u001F'. <lang java> public class Trims{

  public static String ltrim(String s){
     int i = 0;
     while (i < s.length() && Character.isWhitespace(s.charAt(i))){
        i++;
     }
     return s.substring(i);
  }
  public static String rtrim(String s){
     int i = s.length() - 1;
     while (i > 0 && Character.isWhitespace(s.charAt(i))){
        i--;
     }
     return s.substring(0, i + 1);
  }
  public static void main(String[] args){
     String s = " \t \r \n String with spaces  \t  \r  \n  ";
     System.out.println(ltrim(s));
     System.out.println(rtrim(s));
     System.out.println(s.trim()); //trims both ends
  }

}</lang>

Objective-C

Works with: Cocoa
Works with: GNUstep

<lang objc>#import <Foundation/Foundation.h>

@interface NSString (RCExt) -(NSString *) ltrim; -(NSString *) rtrim; -(NSString *) trim; @end

@implementation NSString (RCExt) -(NSString *) ltrim {

 NSInteger i;
 NSCharacterSet *cs = [NSCharacterSet whitespaceCharacterSet];
 for(i = 0; i < [self length]; i++)
 {
   if ( ![cs characterIsMember: [self characterAtIndex: i]] ) break;
 }
 return [self substringFromIndex: i];

}

-(NSString *) rtrim {

 NSInteger i;
 NSCharacterSet *cs = [NSCharacterSet whitespaceCharacterSet];
 for(i = [self length] -1; i >= 0; i--)
 {
   if ( ![cs characterIsMember: [self characterAtIndex: i]] ) break;    
 }
 return [self substringToIndex: (i+1)];

}

-(NSString *) trim {

 return [self 

stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; } @end

int main() {

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 NSString *s = @"     this is a string     ";
 NSLog(@"'%@'", s);
 NSLog(@"'%@'", [s ltrim]);
 NSLog(@"'%@'", [s rtrim]);
 NSLog(@"'%@'", [s trim]);


 [pool release];
 return 0;

}</lang>

Perl

<lang perl> use strict;

sub ltrim {

   my $c = shift;
   $c =~ s/^\s+//;
   return $c;

}

sub rtrim {

   my $c = shift;
   $c =~ s/\s+$//;
   return $c;

}

sub trim {

   my $c = shift;
   return ltrim(rtrim($c));

}

my $p = " this is a string ";

print "'", $p, "'\n"; print "'", trim($p), "'\n"; print "'", ltrim($p), "'\n"; print "'", rtrim($p), "'\n";

exit 0;</lang>

QBasic

<lang qbasic> mystring$=ltrim(mystring$) ' remove leading whitespace

mystring$=rtrim(mystring$)           ' remove trailing whitespace
mystring$=ltrim(rtrim(mystring$))    ' remove both leading and trailing whitespace

</lang>

Python

<lang python>>>> s = ' \t \r \n String with spaces \t \r \n ' >>> s ' \t \r \n String with spaces \t \r \n ' >>> s.lstrip() 'String with spaces \t \r \n ' >>> s.rstrip() ' \t \r \n String with spaces' >>> s.strip() 'String with spaces' >>> </lang>

Sather

<lang sather>class MAIN is

   ltrim(s :STR) :STR is
     i ::= 0;
     loop while!(i < s.size);
       if " \t\f\v".contains(s[i]) then
          i := i + 1;
       else
          break!;
       end;
     end;
     return s.tail(s.size - i);
   end;
   rtrim(s :STR) :STR is
     i ::= s.size-1;
     loop while!(i >= 0);
       if " \t\f\v".contains(s[i]) then
          i := i - 1;
       else
          break!;
       end;
     end;
     return s.head(i+1);
   end;
   trim(s :STR) :STR is
      return ltrim(rtrim(s));
   end;


   main is
     p ::= "     this is a string     ";
     #OUT + ltrim(p).pretty + "\n";
     #OUT + rtrim(p).pretty + "\n";
     #OUT + trim(p).pretty + "\n";
   end;

end;</lang>

Smalltalk

Works with: GNU Smalltalk

<lang smalltalk>String extend [

  ltrim [
     ^self replacingRegex: '^[ \t\f\v]+' with: .
  ]
  rtrim [
     ^self replacingRegex: '[ \t\f\v]+$' with: .
  ]
  trim [
     ^self ltrim rtrim.
  ]

]

|a| a := ' this is a string '.

('"%1"' % {a}) displayNl. ('"%1"' % {a ltrim}) displayNl. ('"%1"' % {a rtrim}) displayNl. ('"%1"' % {a trim}) displayNl.</lang>