iOS modify string to have no line spaces - ios

I am pulling tweets from Twitter and using this to convert it into an array:
NSArray *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
Some of the tweets have a large number of new lines and white space, which has become increasingly annoying for the sake of layout.
I want to turn any strings that have multiple lines into a single lined string.
Here is an example string that I need to convert:
I used #ECSliding library with my project but i can’t used with
#UITableView plz provide me the way if u know it.
#kbegeman
& thank u ;
As you can see this mention has a bunch of white space and couple extra lines.
I have tried using this:
NSString *tweet = [currentTweet objectForKey:#"text"];
NSString *trimmedTweet = [tweet stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
And I also tried this:
myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:#"\n" withString:#""];
myString = [myString stringByReplacingstringByReplacingOccurrencesOfString:#" " withString:#""];
Unfortunately, this does not work. Does it have something to do with the way I am reading in the JSON? Am I using that method wrong? Is there any other solution anyone can think of? Any help would be great, thanks!

That method stringByTrimmingCharactersInSet trims chars from the start and end of the receiver. You'll probably want something like:
NSString *trimmedTweet = [tweet stringByReplacingOccurrencesOfString:#"\n" withString:#" "];

Related

Using componentsSeparatedByString with more than one separator string?

I have a string that I need to separate into an array of words. I was using NSArray *words = [cleanText componentsSeparatedByString:#" "]; which worked fine, until I ran into the end of a paragraph resulting in the component "end.\n\nStart".
Is there a way to separate the string into components using " " as well as "\n\n" character? Or is there more correct way to solve this?
You are describing splitting a string using a regular expression such as "\s". If you look at e.g. https://github.com/bendytree/Objective-C-RegEx-Categories/blob/master/RegExCategories.m you can obtain code for splitting on a regular expression match.
Alternatively you can split on a character set by calling componentsSeparatedByCharactersInSet: and use whitespaceAndNewlineCharacterSet.
You can split on the whitespaceAndNewlineCharacterSet. You will get empty “words” when cleanText has more than one split character in a row, and you probably want to filter those out.
NSArray *words = [#"" componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
words = [words filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *_) {
return [object length] > 0;
}]];

Separate a string into different Array

I have a string coming from server , i want to show some part of string in a view and rest part of string in other view .
Thanks for help.
i want to get the last word of last line of first view. i have searched ,but nothing seems to help me. If any one can suggest me something i would be glad to him/her.
NSString *fromIndex = [_categoryWiseNews.article substringWithRange:NSMakeRange(0, lastWordOfFirstView)];
i have tried with substringWithRange but with this you have to know the lastWordOfFirstView index number for breaking the string into two parts, for which i have no idea.
I really don't know what it is that you're asking lastWordOfFirstView might make sense to you because it is relevant to the thing you are working on. But to us it means nothing.
You can separate a string into words in an array doing this...
NSString *string = #"Hello world, this is a string";
NSArray *array = [string componentsSeparatedByString:#" "];
// array is now... [#"Hello", #"world,", #"this", #"is", #"a", #"string"];
Then you can get the last word from it...
NSString *lastWord = [array lastObject];
Use this to get the last word from a sentence:
NSString *lastWord = [[fullSentenceString componentsSeparatedByString:#" "] lastObject];

stringWithFormat returning newline

I am adding objects to a mutable array by selecting choice(s) from my table view and viewing them in a text field. When I use stringWithFormat, the line of code is automatically adding in characters.
Example: I choose Bob from my table view
Bob
When I do a NSLog, it is actually appearing as
(
Bob
)
But what is appearing in the text field is
( Bob)
Because there is
(\n Bob\n)
Here is the code that I am using to rid of the parentheses and replace commas with semicolons.
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
// NSString
combinedForces = [ourForces stringByReplacingOccurrencesOfString:#"," withString:#";"];
// NSString
twoCombindForces = [combinedForces stringByReplacingOccurrencesOfString:#"(" withString:#""];
// NSString
UltmateCombinedForces = [twoCombindForces stringByReplacingOccurrencesOfString:#")" withString:#""];
//personnel is the text field
personnel.text = UltmateCombinedForces;
Question now is : What is a less messy path to get
( Bob)
to appear as
Bob
in my text field?
Solution update: After the following lines:
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
Include the following line of code:
personnel.text = [AllNames componentsJoinedByString:#";"];
That got rid of the (\n Bob\n) extra characters that were showing up in the field. Thank you all for you help and wisdom. =)
Use componentsJoinedByString: after filling the AllNames array:
personnel.text = [AllNames componentsJoinedByString:#";"];
OK, I think I understand what you're trying to do now.
You have an array of names...
NSArray *names = #[#"Bob", #"Sam", #"Dave"];
And you want a string of all these names...
#"Bob; Sam; Dave"
You seem to be separating them with a semi colon though? ; Is that correct?
You can do this with...
NSString *nameList = [names componentsJoinedByString:#"; "];
But I'm not entirely sure that this is what you're trying to achieve.
In NSLog the output expression
(
Bob
)
represents an array. To get rid of the parentheses and newlines instead of
NSLog(#"%#", AllNames[0]);
write
NSLog(#"%#", AllNames[0][0]);
… and please use variable names starting with a lowercase letter.
You can use NSCharacter Set to remove items you don't want.. The below might offer a less messy solution.
NSString *originalText = #"( Bob) ";
NSMutableCharacterSet *unwantedChars = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[unwantedChars addCharactersInString:#"()"];
NSString *refinedText = [[originalText componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString:#""];

Removing \ from NSString (from escape sequences only)

I have tried (searching for) various possible solutions here on SO, in vain. Most of them simply replace all occurrences of backslashes, and don't respect backslashes that should otherwise be untouched.
For instance, if I have a Hi, it\'s me. How\'re you doing?, it should be Hi, it's me. How're you doing?. However, if someone tries to get creative with ASCII art, like
\\// \\// \\//
//\\ //\\ //\\
(WOW even SO won't let me add text as is, the above text needed extra backslashes to be displayed correctly.)
I cannot use [myString stringByReplacingOccurrencesOfString:#"\\" withString:#""]; since it will replace ALL backslashes. I do not want that.
I would like the string to be displayed as is.
NOTE: The strings in question here are values in NSDictionarys received as JSON from a web service. The use is in a service like a chat client, so it is important that text is handled correctly.
ULTRA IMPORTANT NOTE: I'm open to all ideas like library functions, regular expressions, human sacrifices, as long it gets the job done.
try this ...i cannot understand your question but it may help full for you,i think so
- (void)remove:(NSString*)str
{
NSString* const pattern = #"(\"[^\"]*\"|[^, ]+)";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:0
error:nil];
NSRange searchRange = NSMakeRange(0, [str length]);
NSArray *matches = [regex matchesInString:str
options:0
range:searchRange];
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSLog(#"%#", [str substringWithRange:matchRange]);
}
NSLog(#"%#",str);
}
call this method..
NSString* str = #"Hi, it\'s me. How\'re you doing?";
[self remove:str];
then the output is
Hi, it's me. How're you doing?

How do I easily strip just a comma from an NSString?

I have a UILabel with the following text:
Medium, Black
What I intended to do was grab the words in the string and insert each into a mutable array so I could use each title later on to identify something.
Here's how I done this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByString: #" "] mutableCopy];
NSString *size = [chosenOptions objectAtIndex:0];
NSString *colour = [chosenOptions objectAtIndex:1];
I've logged these two NSString and size is returning "Medium," and colour is correctly returning "Black".
My comparison result is always false because of the comma:
itemExists = [[item colour] isEqualToString:colour] && [[item size] isEqualToString:size] ? YES : NO;
That comma causes itemExists to always equal NO.
Would appreciate a simple solution in code please.
The solution needs to only strip commas and not other characters. When dealing with clothing sizes for females I use sizes in a string like this: "[8 UK]" so remove non-alphanumeric characters would remove these. So I really need a solution to deal with just the commas.
Thanks for your time.
Rather than splitting on spaces, you could split on spaces or commas, like this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" ,"]] mutableCopy];
[chosenOptions removeObject:#""];
This would eliminate commas from the size and colour strings.
[yourString stringByReplacingOccurrencesOfString:#"," withString:#""];
easy squeezy lemon peesey
Try this:
NSString * myString = #"Medium, Black";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#", " withString:#""];
NSLog(#"%#xx",newString);

Resources