6

My NSString is like this:

NSString *myString =  
(  
“\n \n 24 K CLUB”,  
“\n \n 3 DOLLAR CAFE”,  
“\n \n A PEACH OF A PARTY”,  
“\n \n A ROYAL AFFAIR CAFE”,  
“\n \n AFFAIRS TO REMEMBER CATERERS”,  
“\n \n AFRIKAN DELI”  )

How to get rid of this new line character and white spaces, so that my new string will be like: newString:

(
"24 K CLUB”,  
"3 DOLLAR CAFE”,  
“A PEACH OF A PARTY”,  
“A ROYAL AFFAIR CAFE”,  
“AFFAIRS TO REMEMBER CATERERS”,  
“AFRIKAN DELI” 
) 

I tried :

myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:@"\n" withString:@""];  
myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:@" " withString:@""];

but unsuccessfully..getting error:

[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x7062200
Hiren
  • 12,720
  • 7
  • 52
  • 72
AKG
  • 398
  • 1
  • 5
  • 23

2 Answers2

13

How about stringByTrimmingCharactersInSet: method? By stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet], it can remove both ends of whitespace and newline characters.

AechoLiu
  • 17,522
  • 9
  • 100
  • 118
  • 2
    Save somebody a few seconds: `[myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];` – Chris Harrison Mar 02 '15 at 06:29
0

Your initial declaration of myString is declaring an NSArray, not a NSString. Your calls to stringByReplacingstringByReplacingOccurrencesOfString: withString: should work on the individual NSStrings. Either iterate the array yourself (see here) to trim the strings, or use makeObjectsPerformSelector: (see here) to handle it.

Community
  • 1
  • 1
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
  • Ok its an NSArray. I tried: NSString *myString = [[NSArray arrayWithArray:myArray] objectAtIndex: 0].. I am able to get array value of 0 index and also able to modify string the way I wanted..now I have this array with huge data..how to do for that...I can't do it individually...how to use foreach loop..I am sorry if my question is to sily..but I am newbie to deal with NSArray and all. – AKG Sep 26 '10 at 23:13