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:#" "];
Related
I have an array where i am trying to remove the access spaces, brackets and " from the nsarray in order to use componentsSeparatedByString:#";"
NSArray *paths = [dic valueForKey:#"PATH"];
for(NSString *s in paths)
{
NSLog(#"String: %#", s);
}
String: (
"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)
this is the output give as show there are spaces, brackets and " how could i remove them
?
As this line is juz a string inside that array "29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043" this line is a string inside the path array and i try using componentsSeparatedByString:#";" it could not be spilt all there are spaces brackets and " inside.
Try stringByTrimmingCharactersInSet:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#"() \n\""];
s = [s stringByTrimmingCharactersInSet:charsToTrim];
try to use:
s = [s stringByReplacingOccurrencesOfString:#";"
withString:#""];
it separates the numbers for you and you can work with them as i.e. NSInteger values.
NSString *_inputString = #"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043";
NSString *_setCommonSeparator = [_inputString stringByReplacingOccurrencesOfString:#";" withString:#","];
NSArray *_separetedNumbers = [_setCommonSeparator componentsSeparatedByString:#","];
for (NSString *_currentNumber in _separetedNumbers) {
NSInteger _integer = [_currentNumber integerValue];
NSLog(#"number : %d", _integer);
}
I'd like to replace angle brackets and spaces in a string. For example #"< something >" goes to #"something". I'm currently trying:
NSString *s1 = #"< something >";
NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:#"[<> ]"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, s1.length)];
However I'm brand new to regular expressions and #"[<> ]" doesn't seem to work. What's the correct regular expression to use to remove angle brackets and spaces?
Note the documentation for NSRegularExpressionSearch:
You can use this option only with the rangeOfString:... methods.
So even if you had the right regex, you wouldn't be able to use it with this method.
For the situation you describe, it'll probably be easier to use -stringByTrimmingCharactersInSet: with a character set that includes '<' and ' '.
Update: Joshua Weinberg points out that you'd like to remove all occurrences of the characters '<', '>', and ' '. If that's the case, you'll want to look to NSRegularExpression's -stringByReplacingMatchesInString:options:range:withTemplate: method:
NSError *error = nil;
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:#"<> " options:0 error:&error];
NSString *s1 = #"< something >";
NSRange range = NSMakeRange(0, s1.length);
NSString *s2 = [re stringByReplacingMatchesInString:s1 options:0 range:range withTemplate:#""];
(I haven't tested that, but it should point you in the right direction.)
Here is a solution that strips out the characters: '<','>',' '
NSCharacterSet*mySet = [NSCharacterSet characterSetWithCharactersInString:#"<> "];
NSString *s1 = #"< something >";
NSArray * components = [s1 componentsSeparatedByCharactersInSet:
mySet];
NSMutableString * formattedS1 = [NSMutableString string];
for (NSString * s in components) {
[formattedS1 appendString:s];
}
NSLog(#"formatted string %#", formattedS1);
You can add whatever characters you need in the future to the first line
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]];
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.