Remove characters from NSString? - objective-c

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.

Related

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

Remove Special Character From String

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:#" "];

Remove all whitespaces from NSString

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]];

How can I parse this string using NSString?

I have the following string:
callback({"Outcome":"Success", "Message":null, "Identity":"Request", "Delay":0.002, "Symbol":"AAPL", "CompanyName":"Apple Inc.", "Date":"1\/13\/2011", "Time":"4:02:36 PM", "Open":344.6, "Close":345.93, "PreviousClose":344.42, "High":346.63, "Low":343.86, "Last":345.93, "Change":1.51, "PercentChange":0.438, "Volume":785960})
I want my final string to not contain callback( and the the last ) at the end of the string. How can I modify this NSString?
NSScanner is a good fit for this sort of thing.
NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:fullString];
[scanner scanUpToString:#"{" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:#")" intoString:&json];
NSLog(#"json = %#", json);
Make an NSMutableString out of it, called string. i.e. NSMutableString *string = [NSMutableString stringWithString:myString];.
Then do string = [string substringToIndex:[string length]-1]; and then string = [string substringFromIndex:9]; or some such.
Or, again create an NSMutableString instance with your NSString instance, and call [string replaceOccurrencesOfString:#"callback(" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])]; and [string replaceOccurrencesOfString:#")" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])];. This might be preferred.
Either way, then create an NSString instance with the new string, something like goodString = [NSString stringWithString:string]; if you need an NSString out of this.
You can't modify an NSString (only an NSMutableString), but you can use [string substringWithRange:NSMakeRange(9, [string length] - 10)]. To actually mutate an NSMutableString, you'd have to use two deleteCharactersInRange: calls to trim the parts you don't want.

Collapse sequences of white space into a single character and trim string

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.