I've been trying to get rid of the white spaces in an NSString, but none of the methods I've tried worked.
I have "this is a test" and I want to get "thisisatest".
I've used whitespaceCharacterSet, which is supposed to eliminate the white spaces.
NSString *search = [searchbar.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
but I kept getting the same string with spaces. Any ideas?
stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle.
1) If you need to remove only a given character (say the space character) from your string, use:
[yourString stringByReplacingOccurrencesOfString:#" " withString:#""]
2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet then joining the words again in one string:
NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:#""];
Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the stringByReplacingOccurrencesOfString:withString:. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method.
I prefer using regex like this:
NSString *myString = #"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:#"\\s"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [myStringlength])];
//myNewString will be #"thisisatest"
You can make yourself a category on NSString to make life even easier:
- (NSString *) removeAllWhitespace
{
return [self stringByReplacingOccurrencesOfString:#"\\s" withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [self length])];
}
Here is a unit test method on it too:
- (void) testRemoveAllWhitespace
{
NSString *testResult = nil;
NSArray *testStringsArray = #[#""
,#" "
,#" basicTest "
,#" another Test \n"
,#"a b c d e f g"
,#"\n\tA\t\t \t \nB \f C \t ,d,\ve F\r\r\r"
,#" landscape, portrait, ,,,up_side-down ;asdf; lkjfasdf0qi4jr0213 ua;;;;af!####$$ %^^ & * * ()+ + "
];
NSArray *expectedResultsArray = #[#""
,#""
,#"basicTest"
,#"anotherTest"
,#"abcdefg"
,#"ABC,d,eF"
,#"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!####$$%^^&**()++"
];
for (int i=0; i < [testStringsArray count]; i++)
{
testResult = [testStringsArray[i] removeAllWhitespace];
STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], #"Expected: \"%#\" to become: \"%#\", but result was \"%#\"",
testStringsArray[i], expectedResultsArray[i], testResult);
}
}
Easy task using stringByReplacingOccurrencesOfString
NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:#" " withString:#""];
This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.
NSString* yourString = [yourString stringByReplacingOccurrencesOfString:#"\u00a0" withString:#""];
When yourString was the current phone number.
stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end
Use
[YourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
This for me is the best way SWIFT
let myString = " ciao \n ciao "
var finalString = myString as NSString
for character in myString{
if character == " "{
finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")
}else{
finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")
}
}
println(finalString)
and the result is : ciaociao
But the trick is this!
extension String {
var NoWhiteSpace : String {
var miaStringa = self as NSString
if miaStringa.containsString(" "){
miaStringa = miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
}
return miaStringa as String
}
}
let myString = "Ciao Ciao Ciao".NoWhiteSpace //CiaoCiaoCiao
That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use
xyz =[xyz.text stringByReplacingOccurrencesOfString:#" " withString:#""];
It will replace empty space with no space and empty field is taken care of by below method:
searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
Use below marco and remove the space.
#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
in other file call TRIM :
NSString *strEmail;
strEmail = TRIM(#" this is the test.");
May it will help you...
I strongly suggest placing this somewhere in your project:
extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func trim(withSet: NSCharacterSet) -> String {
return self.stringByTrimmingCharactersInSet(withSet)
}
}
pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Related
I have a string that looks like this:
(
TEST STRING
)
I want to remove the parentheses and the white spaces between the parentheses, but not remove the white space within the string.
Basically, I just want the string. I looked into trimming and replacing, but I don't think they applied here.
Any hint on how to go on about solving this problem?
Thanks
This should work:
NSString *originalString = #"( TEST STRING )";
NSString *newString = [originalString stringByReplacingOccurrencesOfString:#"( " withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#" )" withString:#""];
I would consider using (NSRegularExpressionSearch | NSAnchoredSearch)
something like this (I'm writing code on the fly so its probably not correct.
NSRange rng = [myString rangeOfString:#"([ \t\n\r]*" options:(NSRegularExpressionSearch | NSAnchoredSearch)];
NSRange rng = [myString rangeOfString:#"[ \t\n\r]*)" options:(NSRegularExpressionSearch | NSAnchoredSearch | NSBackWardsSearch)];
if ( rng.length && rng2.length )
{
myString = [myString substringToIndex:rng2.location];
myString = [myString substringFromIndex:rng.location];
}
Remove the ()
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"()"]];
And trim the white space.
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSCharacterSet *unwantedChar = [NSCharacterSet characterSetWithCharactersInString:#" "#"\"-[}()\n "];
NSString *requiredString = [[string componentsSeparatedByCharactersInSet:unwantedChar] componentsJoinedByString: #""];
I have a String W
NSString * stringTitle = link.title;
where i am getting link.title as #"I_AM_GOOD";
I need to remove the special characters "_" and make is as "I am Good".How to do that?
You haven't defined what you mean by a special character, and you seem to want to replace it with a space, not remove it.
NSArray * comps = [stringTitle componentsSeparatedByString:#"_"]
NSString * result = nil;
for(NSString *s in comps)
{
if(result)
{
result = [result stringByAppendingFormat:#" %#",[s capitalizedString];
}
else
{
result = [s capitalizedString];
}
}
If you have other special characters that you want to replace, then use
-componentsSeparatedByCharactersInSet:
Easiest way to replace any characeter from a string is as below. Make sure that you use a NSMutableString.
[stringTitle replaceOccurrencesOfString:#"_" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[stringTitle length])];
The most easiest way to do it
strTest = [strTest stringByReplacingOccurrencesOfString:#"_" withString:#" "];
I want to check if a particular string is just made up of spaces. It could be any number of spaces, including zero. What is the best way to determine that?
NSString *str = #" ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
// String contains only whitespace.
}
Try stripping it of spaces and comparing it to #"":
NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:#""];
It's significantly faster to check for the range of non-whitespace characters instead of trimming the entire string.
NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSRange range = [string rangeOfCharacterFromSet:inverted];
BOOL empty = (range.location == NSNotFound);
Note that "filled" is probably the most common case with a mix of spaces and text.
testSpeedOfSearchFilled - 0.012 sec
testSpeedOfTrimFilled - 0.475 sec
testSpeedOfSearchEmpty - 1.794 sec
testSpeedOfTrimEmpty - 3.032 sec
Tests run on my iPhone 6+.
Code here. Paste into any XCTestCase subclass.
Try this:
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
or
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
I'm really surprised that I am the first who suggests Regular Expression
NSString *string = #" ";
NSString *pattern = #"^\\s*$";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSArray *matches = [expression matchesInString:string options:0 range:NSMakeRange(0, string.length)];
BOOL isOnlyWhitespace = matches.count;
Or in Swift:
let string = " "
let pattern = "^\\s*$"
let expression = try! NSRegularExpression(pattern:pattern)
let matches = expression.matches(in: string, range: NSRange(string.startIndex..., in: string))
let isOnlyWhitespace = !matches.isEmpty
Alternatively
let string = " "
let isOnlyWhitespace = string.range(of: "^\\s*$", options: .regularExpression) != nil
Have to use this code for Swift 3:
func isEmptyOrContainsOnlySpaces() -> Bool {
return self.trimmingCharacters(in: .whitespaces).characters.count == 0
}
Trim space and check for number of characters remaining. Take a look at this post here
Here is an easily reusable category on NSString based on #Alexander Akers' answer, but that also returns YES if the string contains "new lines"...
#interface NSString (WhiteSpaceDetect)
#property (readonly) BOOL isOnlyWhitespace;
#end
#implementation NSString (WhiteSpaceDetect)
- (BOOL) isOnlyWhitespace {
return ![self stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]].length;
}
#end
and for those of you untrusting souls out there..
#define WHITE_TEST(x) for (id z in x) printf("\"%s\" : %s\n",[z UTF8String], [z isOnlyWhitespace] ? "YES" :"NO")
WHITE_TEST(({ #[
#"Applebottom",
#"jeans\n",
#"\n",
#""
"",
#" \
\
",
#" "
];}));
➜
"Applebottom" : NO
"jeans
" : NO
"
" : YES
"" : YES
" " : YES
" " : YES
Here's the Swift version code for the same,
var str = "Hello World"
if count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 {
// String is empty or contains only white spaces
}
else {
// String is not empty and contains other characters
}
Or you can write a simple String extension like below and use the same code with better readability at multiple places.
extension String {
func isEmptyOrContainsOnlySpaces() -> Bool {
return count(self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0
}
}
and just call it using any string like this,
var str1 = " "
if str.isEmptyOrContainsOnlySpaces() {
// custom code e.g Show an alert
}
Here is a simple Swift solution:
//Check if string contains only empty spaces and new line characters
static func isStringEmpty(#text: String) -> Bool {
let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let newText = text.stringByTrimmingCharactersInSet(characterSet)
return newText.isEmpty
}
NSString *myString = #"A B C D E F G";
I want to remove the spaces, so the new string would be "ABCDEFG".
You could use:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.
All above will works fine. But the right method is this:
yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
It will work like a TRIM method. It will remove all front and back spaces.
Thanks
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
You can try this
- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:#" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
}
return str;
}
Hope this will help you out.
Consider the following example:
" Hello this is a long string! "
I want to convert that to:
"Hello this is a long string!"
OS X 10.7+ and iOS 3.2+
Use the native regexp solution provided by hfossli.
Otherwise
Either use your favorite regexp library or use the following Cocoa-native solution:
NSString *theString = #" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:#" "];
Regex and NSCharacterSet is here to help you. This solution trims leading and trailing whitespace as well as multiple whitespaces.
NSString *original = #" Hello this is a long string! ";
NSString *squashed = [original stringByReplacingOccurrencesOfString:#"[ ]+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
NSString *final = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Logging final gives
"Hello this is a long string!"
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Performance rundown
This solution: 7.6 seconds
Splitting, filtering, joining (Georg Schölly): 13.7 seconds
Ease of extension, performance, number lines of code and the number of objects created makes this solution appropriate.
Actually, there's a very simple solution to that:
NSString *string = #" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", trimmedString)
(Source)
With a regex, but without the need for any external framework:
NSString *theString = #" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:#" +" withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
A one line solution:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString
stringByReplacingOccurrencesOfString:#" " withString:#""];
This should do it...
NSString *s = #"this is a string with lots of white space";
NSArray *comps = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *words = [NSMutableArray array];
for(NSString *comp in comps) {
if([comp length] > 1)) {
[words addObject:comp];
}
}
NSString *result = [words componentsJoinedByString:#" "];
Another option for regex is RegexKitLite, which is very easy to embed in an iPhone project:
[theString stringByReplacingOccurencesOfRegex:#" +" withString:#" "];
Try This
NSString *theString = #" Hello this is a long string! ";
while ([theString rangeOfString:#" "].location != NSNotFound) {
theString = [theString stringByReplacingOccurrencesOfString:#" " withString:#" "];
}
Here's a snippet from an NSString extension, where "self" is the NSString instance. It can be used to collapse contiguous whitespace into a single space by passing in [NSCharacterSet whitespaceAndNewlineCharacterSet] and ' ' to the two arguments.
- (NSString *) stringCollapsingCharacterSet: (NSCharacterSet *) characterSet toCharacter: (unichar) ch {
int fullLength = [self length];
int length = 0;
unichar *newString = malloc(sizeof(unichar) * (fullLength + 1));
BOOL isInCharset = NO;
for (int i = 0; i < fullLength; i++) {
unichar thisChar = [self characterAtIndex: i];
if ([characterSet characterIsMember: thisChar]) {
isInCharset = YES;
}
else {
if (isInCharset) {
newString[length++] = ch;
}
newString[length++] = thisChar;
isInCharset = NO;
}
}
newString[length] = '\0';
NSString *result = [NSString stringWithCharacters: newString length: length];
free(newString);
return result;
}
Alternative solution: get yourself a copy of OgreKit (the Cocoa regular expressions library).
OgreKit (Japanese webpage --
code is in English)
OgreKit (Google
autotranslation):
The whole function is then:
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:#"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:#" "]);
Short and sweet.
If you're after the fastest solution, a carefully constructed series of instructions using NSScanner would probably work best but that'd only be necessary if you plan to process huge (many megabytes) blocks of text.
according from #Mathieu Godart is best answer, but some line is missing , all answers just reduce space between words , but when if have tabs or have tab in place space , like this:
" this is text \t , and\tTab between , so on "
in three line code we will :
the string we want reduce white spaces
NSString * str_aLine = #" this is text \t , and\tTab between , so on ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:#"\t" withString:#" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:#" +" withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
the result is
"this is text , and Tab between , so on"
without replacing tab the resul will be:
"this is text , and Tab between , so on"
You can also use a simple while argument. There is no RegEx magic in there, so maybe it is easier to understand and alter in the future:
while([yourNSStringObject replaceOccurrencesOfString:#" "
withString:#" "
options:0
range:NSMakeRange(0, [yourNSStringObject length])] > 0);
Following two regular expressions would work depending on the requirements
#" +" for matching white spaces and tabs
#"\\s{2,}" for matching white spaces, tabs and line breaks
Then apply nsstring's instance method stringByReplacingOccurrencesOfString:withString:options:range: to replace them with a single white space.
e.g.
[string stringByReplacingOccurrencesOfString:regex withString:#" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
Note: I did not use 'RegexKitLite' library for the above functionality for iOS 5.x and above.