Set newline and paragraph in string with objective C - iphone

When i parse the jason url i got string with character \n \r ... Now i want break the line where with "\n" and put the paragraph with "\r".
i got string like this.
description = "Black Chasm Cavern was designated a National Natural Landmark by the National Park Service in 1976 after being recommended by local members of the National Speleological Society, and as such is considered a \"nationally significant natural area.\U201d\n\nVisitors to the cave are enchanted by the beauty of a wide variety of formations including stalactites, stalagmites, flowstones and the vast arrays of rare helictite crystals, for which Black Chasm is justly famous.\n\nThe 45-minute walk tour follows a series of platforms, stairs and walkways designed to give the best views of the cave without compromising the naturally pristine environment. Currently, the tour culminates in a visit to the Landmark Room, the location of the greatest collections of sparkling helictite crystals.\n\nAbove ground, kids love our gemstone mining at our mining flumes right outside the Visitors Center. Everyone is guaranteed to find some real gemstones; the perfect start to a rock collection! Try our new incredibly popular geode cracking too!";
and i want to display this string in label as per format.
how can i do this job if any one have any idea please tell me ...
Thanks.

I would suggest iterating through your string, separating it into an array of lines and paragraphs. Like the following.
NSArray *lines = [string componentsSeparatedByString:#"\n"];
for(NSString *line in lines)
{
NSArray *lineElements = [line componentsSeparatedByString:#"\r"];
// do something with lineElements
}

Related

Most efficient way to locate a the presence of a substring in a dictionary (NLP)

I'm currently working on a speech recognition feature, where a user can say a command and have that command trigger an event.
The way I have it structured now does work, but mostly because the recognition dictionary is small. It likely will never be millions of commands, but that's no reason to be sloppy.
Here is how it works now:
#ObservedObject var speechText
private var matchables: [String:Int] = [["start the action",0], //formal
["start action",0], //informal
["star traction",0], //common misfire by NLU
["stop the action",1]] //different action
//Call processText with lowercase speechText
//when Observed string value changes
//assume text is conversational, such as "Jenny, I like chicken, also device why
//don't you start the action"
func processText(text: String) {
for (key, value) in matchables {
if text.contains(key) {
executeActionByID(value)
}
}
}
This will loop through the matchables collection and search for the contents of each key inside of the text value. This works fine on a small dictionary, but becomes cumbersome at scale.
I could theoretically break text into N-Grams and then access the dictionary directly by key, but this is long running recognition, and text might contain a substantial number of words (hundreds?) which may exceed the maximum practical size of the dictionary.
Is there a third, better way to analyze long running streams of text and quickly pick out commands that match a small substring?
Here is my back-of-the envelope thinking about this problem:
Searching for keys in a Dictionary is really fast (almost constant time). Searching strings for substrings using String.contains(_:) is slow. (Around O(n) where n is the length of the string.)
As your string length goes up and your number of keys goes up, your time to completion is going to go up by O(n*x) (n=string length, x = number of keys.)
That's likely to get slow for longer search strings, and total time will grow geometrically if both your number of keys and string length increase.
I'd suggest breaking your string into discrete units to search for (the obvious way is to divide it with spaces and other separators like punctuation.) If you do that you could check to see if each word appears in your dictionary keys. That should get you roughly O(n) time performance, since each search for a key in a dictionary runs in nearly constant time.

How to Display International Accents with Quartz/Core Graphics on iPhone

I've localized an app for the iPhone. No surprise, the localization includes some accents:
"Touch cards to select. Then touch
'Bid'." = "Touchez les cartes pour les
sélectionner, puis touchez 'Miser'.";
These work fine in high-level stuff, like when I put the text into a table, but when I try to write them to a UIView by hand, the accents get mangled:
I'm using kCGEncodingMacRoman and UTF8, both of which should support accents, I think, but I'm clearly missing something:
CGContextSelectFont(ctx,fontName,thisWriting.fontSize,kCGEncodingMacRoman);
CGContextShowTextAtPoint(ctx,
thisWriting.center.x - floor(thisTextSize.width/2),
yThusFar,
[thisText UTF8String],
[thisText length]);
The font is some variant of ArialMT. thisText is just an NSString.
Quartz provides a limited, low-level interface for drawing text. For information on text-drawing functions, see CGContext Reference. For full Unicode and text-layout support, use the services provided by Core Text or ATSUI).
To expand on what sorin said: Quartz/Core Graphics do not support Unicode text, which includes the accents you need for foreign languages. There have traditionally been a number of alternative ways to resolve this, but currently the best answer is to use Core Text, which can write directly to a graphical context, as I was doing here.
The main element in Core Text is the NSAttributedString or NSMutableAttributed String class.
Here's similar code to what I had for Core Text:
CTLineRef thisLine = CTLineCreateWithAttributedString((CFAttributedStringRef)thisAText);
CGContextSetTextPosition(ctx, self.center.x - floor(thisTextSize.width/2), yThusFar);
CTLineDraw(thisLine, ctx);
The font is already taken care of, because it's part of that NSAttributedString (or CFAttributedStringRef, which is a toll-free bridged equivalent).
Here's the result:

How to store text as paragraphs in SQLite database in a iPhone app?

In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.
What should I do to store the text as paragraphs in SQLite database?
For example, I want to store paragraphs like the ones below in:
(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.
The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'
Basically I want to save the paragraphs in database in the same format with carriage returns.
It depends on what you mean by huge and how you're planning on showing the data. The SQLite TEXT field, by default, can store 1 billion bytes.
You could in theory store all of it in a TEXT field in SQLite, then render it in a UIScrollView (or whatever it is you're using to render) and check the performance, memory usage, etc.
If the performance is unacceptable, you can try "chunking" the text into multiple rows and displaying only the records of the text required for the UI.
See the SQLite Limits document:
Maximum length of a string or BLOB
The maximum number of bytes in a string or BLOB in SQLite is defined by
the preprocessor macro
SQLITE_MAX_LENGTH. The default value
of this macro is 1 billion (1 thousand
million or 1,000,000,000). You can
raise or lower this value at
compile-time using a command-line
option like this:
-DSQLITE_MAX_LENGTH=123456789
On the face of it, SQLite doesn't treat newlines any differently than other characters; you can just store the test as-is.
The issue, though, is why are you storing large volumes of raw text in SQLite? If you want to search it or organize it somehow, SQLite (nor Core Data) is probably not the best choice without first massaging the text into some other form. Or, alternatively, you'd want to store the raw text on disk then keep some kind of searchable index in the database.
My suggestion would be if you want to display your text in a webview then add HTML tags to your text.So in that way you can add paragraphs,New lines and many other effects to your text.
Thanks
so do you want to split the text into paragraph and store each in its own row like:
(paragraph_number, text_of_paragraph)
that would be:
create table paragraphs (paragraph_number, text_of_paragraph);
then in what ever language you use split the text into a list of (pn, tp) named l and do like:
executemany("insert into paragraphs values (?, ?)", l)
or do like:
for p in l:
execute("insert into paragraphs values (?, ?)", p)
i would use HTML to represent my paragraphs (i.e)
Saving the Text
<div>
<p>(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.</p>
<p>The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.</p>
</div>
Loading the Paragraphs
I would load them inside a UIWebView as html, you can save the HTML into a file in the app sandbox let's say Paragraph1.HTML load it as the following:
// this is a user defined method
-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
NSURL *url = [NSURL fileURLWithPath:sFilePath];// Path of the HTML File
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[web loadRequest:request];
}
dispose the File after loading it, this will save you much time and space.
Good luck.

Problems with escaped characters in JSON string

I have a JSON-string where I know where the problem is, I just can't figure out what to do. I have looked up the "forbidden characters" in a JSON-string but it just doesn't work.
When you run the show-method for FBStreamDialog for iPhone a view comes up with how it's going to look like when it's finally posted on the wall.
This happends when the "description"-property in my JSON-string is hard coded like #"Testing". But as soon as I add the text fetched from a data source which looks like this, it doesn't work:
"description":"
LIVE: Uk's No:1 Reggae Singer Bitty Mclean + Joey Fever, Sthlms No:1 Reggae Voice.
DJs
Deejay Flash & Micke Goulos + Mc Fabulous G.
The Vinyl Bar
Up...
"
Note: I only show the "description"-property of the JSON-string, because there is where the problem is.
So what I tried to do was, as I've explained before, to add the string "Testing" in the "description"-property. This worked. But I wanted to have the data source property of "description", of course. So I tried to replace all the characters that isn't a letter with this code:
shortString = [shortString stringByReplacingOccurrencesOfString:#"&" withString:#"och"];
shortString = [shortString stringByReplacingOccurrencesOfString:#"+" withString:#"plus"];
shortString = [shortString stringByReplacingOccurrencesOfString:#"," withString:#"komma"];
shortString = [shortString stringByReplacingOccurrencesOfString:#"'" withString:#"apostrof"];
shortString = [shortString stringByReplacingOccurrencesOfString:#":" withString:#"colon"];
The output of that is:
"description":"LIVEcolon Ukapostrofs Nocolon1 Reggae Singer Bitty Mclean plus Joey Feverkomma Sthlms Nocolon1 Reggae Voice.
DJs
Deejay Flash och Micke Goulos plus Mc Fabulous G.
The Vinyl Bar
Up...
Which looks like a approvable JSON string?
But apparently not, because the facebook view never shows how it's going to look if I use the data source "description"-property. It just shows the text box "What's on your mind".
This is driving me crazy.
Finally!
I understand why you didn't answer this question. How could you know that facebook connect doesn't allow \n in their StreamDialog's. Not for iPhone anyway.
So the solution was to replace \n with a whitespace or whatever you want.

Drawing Unicode characters on iPhone

Why is it so hard to figure out how to draw Unicode characters on the iPhone, deriving simple font metrics along the way, such as how wide each imaged glyph is going to be in the font of choice?
It looks like it'd be easy with NSLayoutManager, but that API apparently isn't available on the phone. It appears the way people are doing this is to use a private API, CGFontGetGlyphsForUnichars, which won't get you past the Apple gatekeepers into the App store.
Can anybody point me to documentation that shows how to do this? I'm losing hair rapidly.
Howard
I assumed that the exclusion of CGFontGetGlyphsForUnichars
was an oversight rather than a deliberate move, however I'm not
betting the farm on it. So instead I use
[NSString drawAtPoint:withFont:]; (in UIStringDrawing.h)
and
[NSString sizeWithFont];
This also has the advantage of performing decent substitution
on characters missing from your font, something that
CGContextShowGlyphs does not do.
CoreText is the answer if you want to draw unicode rather than CGContextShowGlyphsAtPositions. Also it's better than [NSString drawAtPoint:withFont:] if you need custom drawing.
Here is a complete example:
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attributedString);
CFArrayRef runArray = CTLineGetGlyphRuns(line);
//in more complicated cases make loop on runArray
//here I assumed this array has only 1 CTRunRef within
const CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, 0);
//do not use CTFontCreateWithName, otherwise you won't see e.g. chinese characters
const CTFontRef font = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
CFIndex glyphCount = CTRunGetGlyphCount(run);
CGGlyph glyphs[glyphCount];
CGPoint glyphPositions[glyphCount];
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs);
//you can modify positions further
CTRunGetPositions(run, CFRangeMake(0, 0), glyphPositions);
CTFontDrawGlyphs(font, glyphs, glyphPositions, glyphCount, context);
CFRelease(line);
I've made a pretty suitable replacement for the private function. Read about it here:
http://thoughts.codemelody.com/2009/07/a-replacement-for-cgfontgetglyphsforunichars/