Strip whitespace from a string/Top and tail
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>
- include <stdlib.h>
- include <string.h>
- 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
<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>
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>
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>