NSString nslog revealing "\n" newline character - objective-c

I want to log an NSString but when I log it, it doesn't show the new line character "
n". How can I make it so it does? Thanks.

You can process the string first and replace all occurrences of \n with \\n
NSString *newString = [originalString stringByReplacingOccurrencesOfString:#"\n" withString:#"\\n"];

Related

Trimmed string change it's length only by half

Could anyone give some advise please.
In my iOS app I am parsing XML (with a help of third-party-library) and have a problem with extra whitespaces/newLines at the beginning/end of the strings. Initial string, that return this third-party-library, it's a C++ std::wstring that I convert to NSString (the encoding should be right as the content of new NSString is equal to proper part of my XML-file). After the trim length of "empty" elements (that contain only whitespaces and new lines) doesn't become zero but change it's value by half.
The code is below....
std::wstring val;
NSString *initial = [[NSString alloc] initWithBytes:val.data() length:sizeof (wchar_t)*val.size() encoding:NSUTF16LittleEndianStringEncoding];
NSString *trimmed = [initial stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
If try to output like NSLog(#"bybyby'%#'bebebe", trimmed); 'bebebe have never displayed. Looks like that there are left some new lines, whitespaces that can't be detected.
wchar_t is a 32-bit integer (on iOS and OS X), therefore you must use NSUTF32LittleEndianStringEncoding for the conversion to NSString.
Example:
std::wstring val (L" Hello World ");
NSString *initial = [[NSString alloc] initWithBytes:val.data() length:sizeof (wchar_t)*val.size() encoding:NSUTF32LittleEndianStringEncoding];
NSString *trimmed = [initial stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"'%#'", trimmed);
// Output: 'Hello World'
What probably happened in your case (with NSUTF16LittleEndianStringEncoding)
is that every second character in the initial string is a NUL character,
which acts as a terminator when printed.

line break at starting of UILabel text

I have string to display in UILabel, but the UILabel isn't displaying the text of the below string.
string is : " \n \n If you are using a corticosteroid medication"
I know \n at the start isn't logical but I am getting it from server and hence I can not change it. So is there any way to resolve this issue.
Any way that label displays rest text by adding two line break at start or how can I truncate \n if it is in the beginning of string.
Thanks.
Did you try this?
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
If you are wanting to remove \n from your string you could just use something as simple as
NSString *myString = #" \n \n If you are using a corticosteroid medication";
myString = [[myString stringByReplacingOccurrencesOfString:#"\n"
withString:#""];
stringByReplacingOccurencesOFString: withString: will replace all occurrences of the given string (In your case \n) with the given string.
The above should technically do the exact same as [myString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
If you want to replace only within a specific range then you could use stringByReplacingOccurrencesOfString:withString:options:range: instead like:
myString = [myString replaceOccurencesOfString:#"\n"
withString:#""
options:NULL
range:NSMakeRange(0, 7)];
This will remove all occurrences of \n within the given range, for this example from 0 - 7
Check out he Apple documentation for this here
Try this
NSString *text = #" \n \n If you are using a corticosteroid medication";
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

rangeOfString doesn´t recognize Substring

I have this behaviour I can´t understand.
NSString *title = [[PushNotifcationManager getPushNotificationSettingsForKey:#"settings"] objectForKey:#"title"];
NSLog(#"title: %#",title); //Outputs Test\ntest
if([title rangeOfString:#"\n"].location == NSNotFound){
//String contains no \n
}else{
//String contains \n
}
Even though the String clearly contains "\n" the [title rangeOfString:#"\n"].location == NSNotFound returns true.
NSLog("%#") does not escape backslash characters in strings, so the output
Test\ntest means that your string contains a backslash character followed by a n,
not a newline character.
Therefore you have to check for
[title rangeOfString:#"\\n"]
where \\ in a string literal stands for one backslash character.

Trim whitespace in between characters

i just updated to ios 7 sdk, and I would like to trim/replace the whitespace between characters of a string whereby the numbers are taken out from ABAddressBook.
I have tried using the replace " " with "" code below, but this code doesnt seems to work in ios7 sdk, it works fine in ios 6 sdk by the way.
NSString *TrimmedNumberField = [self.numberField.text
stringByReplacingOccurrencesOfString:#" " withString:#""];
is there any other way I could do it in IOS 7?
EDIT:
It's a phone number type that I'm trying.
Input: "+65 12 345 6789"
The output i got from NSLog is " 12 345 6789"
I realized that when I added into NSDictionary and view it in NSLog, it appears that it contains a unix code representation of \u00a0 which is similar to the "dot in the middle" which is not equals to a fullstop.
thanks in advance.
Found the answer from here
phoneNumber = [phoneNumber stringByReplacingOccurencesOfString:#"." withString:#""];
// where #"." was created by typing Option+ Spacebar
The number is extracted from ABAddressbook.
You can loop over the string and remove whitespace as long as there is any
NSString *someString = #"A string with multiple spaces and other whitespace.";
NSMutableString *mutableCopy = [someString mutableCopy];
// get first occurance of whitespace
NSRange range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
// If there is a match for the whitespace ...
while (range.location != NSNotFound) {
// ... delete it
[mutableCopy deleteCharactersInRange:range];
// and get the next whitespace
range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
}
// no more whitespace. You can get back to an immutable string
someString = [mutableCopy copy];
The result with the string above is Astringwithmultiplespacesandotherwhitespace.
Try This:
NSString *str = #" untrimmed string ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Try This
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
whitespaceCharacterSet Apple Documentation for iOS says
Returns an NSData object encoding the receiver in binary format.
(NSData *)bitmapRepresentation
Return Value
An NSData object encoding the receiver in binary format.
Discussion
This format is suitable for saving to a file or otherwise transmitting or archiving.
A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following:
So Try This
NSString *testString = #" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Objective-C – Replace newline sequences with one space

How can I replace newline (\n) sequences with one space.
I.e the user has entered a double newline ("\n\n") I want that replaced with one space (" "). Or the user has entered triple newlines ("\n\n\n") I want that replaced with also one space (" ").
Try this:
NSArray *split = [orig componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
split = [split filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
NSString *res = [split componentsJoinedByString:#" "];
This is how it works:
First line splits by newline characters
Second line removes empty items inserted for multiple separators in a row
Third line joins the strings back using a single space as the new separator
3 times more performant than using componentsSeparatedByCharactersInSet
NSString *fixed = [original stringByReplacingOccurrencesOfString:#"\\n+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Replace newlines: \\n+
As wattson says you can do this with NSRegularExpression but the code is quite verbose so if you want to do this at several places I suggestion you to do a helper method or even a NSString category with method like -[NSString stringByReplacingMatchingPattern:withString:] or something similar.
NSString *string = #"a\n\na";
NSLog(#"%#", [[NSRegularExpression regularExpressionWithPattern:#"\\n+"
options:0
error:NULL]
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#" "]);
Use a regular expression, something like "s/\n+/\w/" (a replace which will match 1 or more newline character and replace with a single white space)
this question has a link to a regex library, but there is NSRegularExpression available too