Rendering an ASCII art string with newline characters and backslashes - ios

I am making an app where there is a requirement to store ASCII art into a database. I store the strings in the below format.
"___________\n |---------|-O\n/___________\\n|______________|\n\____________/"
When I retrieve the data and display it in a label, I want the newline characters and backslashes to be parsed so as to display the real shape of the ASCII art.
How should I parse this kind of strings?

NSString has a method to do what you want, which is to replace a litteral \n, with a newline character (which is symbolized as \n). In a c-format string you can use a double slash to let the library know the second slach is a real one and not an escape symbol. So this should work assuming you have been able to load your data from sqlite into an NSString:
newString = [yourStringFromSQLite stringByReplacingOccurrencesOfString:#"\\n" withString:#"\n"];

If you are using \n just for creating new lines then instead of that just keep space while inserting value in database and set following properties for label ->
1)keep width just to fit first word.
2)linebreakmode to wordwrap (so as width will not be available it will wrap next word to new line)
3)set no. of lines to 0
Hope this will help.

try to use the scanner for remove the html entities
- (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:#"<" intoString:NULL] ;
[theScanner scanUpToString:#">" intoString:&text] ;
html = [html stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:#"%#>", text] withString:#" "];
}
return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}
and call this method where your trimmed string need to display

Related

How to trim characters from a position to another position in iOS (Objective C)?

My problem is, i want to trim away some characters from my string. My string contains xml. So i need to trim characters from an xml opening tag upto its closing tag. How can i do it?
Eg: My string contains the following xml codes.
<CategoriesResponse xmlns="https://abc.defg.com/hijk">
<MainCategories>
<CatID xsi:type="xsd:int">178</CatID>
<CatID xsi:type="xsd:int">150</CatID>
<CatID xsi:type="xsd:int">77</CatID>
<CatID xsi:type="xsd:int">33</CatID>
<CatID xsi:type="xsd:int">179</CatID>
</MainCategories>
<SubCategories>
//some needed elements should not be trimmed.
</SubCategories>
i need to trim from the opening tag <MainCategories> to closing tag </MainCategories>.
How to do it?? So here my starting character will be <MainCategories and ending character will be /MainCategories>
Try this
NSString *str = #"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";
NSRange startRange = [str rangeOfString:#"<MainCategories>"];
NSRange endRange = [str rangeOfString:#"</MainCategories>"];
NSString *replacedString = [str stringByReplacingCharactersInRange:NSMakeRange(startRange.location, (endRange.location+endRange.length)-startRange.location) withString:#""];
NSLog(#"%#",replacedString);
Hope this helps.
Try below code:
NSString *strXml=#"<CategoriesResponse xmlns=\"https://abc.defg.com/hijk\"><MainCategories><CatID xsi:type=\"xsd:int\">178</CatID><CatID xsi:type=\"xsd:int\">150</CatID><CatID xsi:type=\"xsd:int\">77</CatID><CatID xsi:type=\"xsd:int\">33</CatID><CatID xsi:type=\"xsd:int\">179</CatID></MainCategories><SubCategories></SubCategories>";
strXml=[strXml stringByReplacingOccurrencesOfString:#"<MainCategories>" withString:#"<MainCategories"];
strXml=[strXml stringByReplacingOccurrencesOfString:#"</MainCategories>" withString:#"/MainCategories>"];
NSLog(#"%#",strXml);
Hope it will help :)

Way to detect character that takes up more than one index spot in an NSString?

I'm wondering, is there a way to detect a character that takes up more than 1 index spot in an NSString? (like an emoji). I'm trying to implement a custom text view and when the user pushes delete, I need to know if I should delete only the previous one index spot or more.
Actually NSString use UTF-16.So it is quite difficult to work with characters which takes two UTF-16 charater(unichar) or more.But you can do with rangeOfComposedCharacterSequenceAtIndexto get range and than delete.
First find the last character index from string
NSUInteger lastCharIndex = [str length] - 1;
Than get the range of last character
NSRange lastCharRange = [str rangeOfComposedCharacterSequenceAtIndex: lastCharIndex];
Than delete with range from character (If it is of two UTF-16 than it deletes UTF-16)
deletedLastCharString = [str substringToIndex: lastCharRange.location];
You can use this method with any type of characters which takes any number of unichar
For one you could transform the string to a sequence of characters using [myString UTF8String] and you can then check if the character has its first bit set to one or zero. If its one then this is a UTF8 character and you can then check how many bytes are there to this character. Details about UTF8 can be found on Wikipedia - UTF8. Here is a simple example:
NSString *string = #"ČTest";
const char *str = [string UTF8String];
NSMutableString *ASCIIStr = [NSMutableString string];
for (int i = 0; i < strlen(str); ++i)
if (!(str[i] & 128))
[ASCIIStr appendFormat:#"%c", str[i]];
NSLog(#"%#", ASCIIStr); //Should contain only ASCII characters

getting certain portion of nsstring

I have string as follows in objective c
NSString *str = #"access_token=E2JmCPLtVySGn-cGGJGGnQ&email=abc#gmail.com";
How can i get only E2JmCPLtVySGn-cGGJGGnQ ?
You can use a Regular Expression (RegEx) to find character patterns.
The pattern matching syntax can be found in the ICU User Guide Regular Expressions
In the example the pattern is: find the first "=" and all characters up to but not including the character "&". In the pattern '(?<=access_token=)" is a look-behind assertion meaning that the "access_token=" must precede the matched text, "[^&]+" the brackets the "[]" mean a character class, the "^" al but the following character, the "+" means one or more.
NSString *str = #"access_token=E2JmCPLtVySGn-cGGJGGnQ&email=abc#gmail.com";
NSString *regexPattern = #"(?<=access_token=)[^&]+";
NSString *found = nil;
NSRange range = [str rangeOfString:regexPattern options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
found = [str substringWithRange:range];
}
NSLog(#"Range: %#", NSStringFromRange(range));
NSLog(#"found: %#", found);
NSLog output if found:
Range: {13, 22}
found: E2JmCPLtVySGn-cGGJGGnQ
There is a method of the NSString class called rangeOfString: that returns an NSRange struct. If you know that your returned value always has the text access_token= and also includes &email and the format is always the same, you can use this rangeOfString: method to sniff out the token.
NSRange accessTokenRange = [str rangeOfString:#"access_token="];
//this would return (0,13) for index:0, length: 13
NSRange emailRange = [str rangeOfString:#"&email="];
//this would return (34,7)
NSInteger tokenLength = ( emailRange.location + 1 ) - accessTokenRange.length;
//the point where &email begins is at index 34, but it starts at 0
//so it's actually the 35th character
//the access_token= string is 13 characters long, so 35-13 = 22
//so you know that the actual token value is 22 characters long
NSRange trueTokenRange = NSMakeRange(accessTokenRange.length,tokenLength);
NSString *tokenSubstring = [str substringWithRange:trueTokenRange];
I don't think my math is off, zero indexing can introduce off by 1 errors if you're not careful, I usually have NSLog going on each range so I can double check where I need to add or subtract 1. But essentially you'll be starting at the 14th character, which is index 13 of the string, and reading the next 22 characters.

How can I search for and remove an escaped character from an NSString?

I am reading a line of code in from a source file on disk and the line is a string, and it is of a string that contains HTML code in it:
line = #"format = #"<td width=\"%#\">";"
I need to remove the escaped characters from the html string. So any place that there is a '\"', I need to replace it with ''. I tried this:
[line stringByReplacingOccurrencesOfString:#"\\""" withString:#""];
But it only removed the '\' character, not the accompanying '"'. How can I remove the escaped '"' from this string?
EDIT: The key part of this problem is that I need to figure out a way to identify the location of the first #", and the closing " of the string declaration, and ignore/remove everything else. If there is a better way to accomplish this I am all ears.
[s stringByReplacingOccurrencesOfString:#"\\\"" withString:#""]
The replacement string there is a slash, which has to be escaped in the literal replacement string using another slash, followed by a quote, which also has to be escaped in the literal by a slash.
Try use this:
NSString *unfilteredString = #"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);

Extract text from a NSString using regular expressions

I have a NSString in this format:
"Key1-Value1,Key2-Value2,Key3-Value3,..."
I need only keys (with a space after every comma):
Key1, Key2, Key3, etc.
I thought to create an array of components from the string using the comma as separator, and after, for every component, extract all characters since the "-"; then I'd serialize the array elements. But I fear this could be very heavy about performances.
Do you know a way to do this using regular expressions?
The regex will greatly depend on the data you are using. For example if the key or value is allowed to be all numbers, or allowed to contain space and punctuation, you would need to modify the regex. For your current example however this will work.
NSString *example = #"Key1-Value1,Key2-Value2,Key3-Value3,...";
NSString *result = [example stringByReplacingOccurrencesOfString:#"(\\w+)-(\\w+),?"
withString:#"$1, "
options:NSRegularExpressionSearch
range:NSMakeRange(0, [example length])];
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
NSLog(#"%#", result);

Resources