Remove newline character from first line of NSString - iphone

How can I remove the first \n character from an NSString?
Edit: Just to clarify, what I would like to do is:
If the first line of the string contains a \n character, delete it else do nothing.
ie: If the string is like this:
#"\nhello, this is the first line\nthis is the second line"
and opposed to a string that does not contain a newline in the first line:
#"hello, this is the first line\nthis is the second line."
I hope that makes it more clear.

[string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
will trim your string from any kind of newlines, if that's what you want.
[string stringByReplacingOccurrencesOfString:#"\n" withString:#"" options:0 range:NSMakeRange(0, 1)]
will do exactly what you ask and remove newline if it's the first character in the string

This should do the trick:
NSString * ReplaceFirstNewLine(NSString * original)
{
NSMutableString * newString = [NSMutableString stringWithString:original];
NSRange foundRange = [original rangeOfString:#"\n"];
if (foundRange.location != NSNotFound)
{
[newString replaceCharactersInRange:foundRange
withString:#""];
}
return [[newString retain] autorelease];
}

Rather than creating an NSMutableString and using a few retain/release calls, you can use only the original string and simplify the code by using the following instead: (requires 10.5+)
NSRange foundRange = [original rangeOfString:#"\n"];
if (foundRange.location != NSNotFound)
[original stringByReplacingOccurrencesOfString:#"\n"
withString:#""
options:0
range:foundRange];
(See -stringByReplacingOccurrencesOfString:withString:options:range: for details.)
The result of the last call method call can even be safely assigned back to original IF you autorelease what's there first so you don't leak the memory.

Related

Replacing instances of a character with two different characters in Objective-C

I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as "This is a message with $specially formatted$ content".
However, I need to change the '$' at the start of the special formatting with a '[' and the '$' at the end with ']'. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!
Is there a simple way to recognise a substring encapsulated by '$' and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple '$' substrings.
Thanks!
You can use regular expressions:
NSMutableString *str = [#"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#"[$1]"];
NSLog(#"%#", str);
// Output:
// Hello [World], foo [bar].
The pattern #"\\$([^$]*)\\$" searches for
$<zero_or_more_characters_which_are_not_a_dollarsign>$
and all occurrences are then replaced by [...]. The pattern contains so many backslashes because the $ must be escaped in the regular expression pattern.
There is also stringByReplacingMatchesInString if you want to create a new string instead of modifying the original string.
I think replaceOccurrencesOfString: won't work cause you have start$ and end$.
But if you seperate the Strings with [string componentsSeperatedByString:#"$"] you get an Array of substrings, so every second string is your "$specially formatted$"-string
This should work!
NSString *str = #"This is a message with $specially formatted$ content";
NSString *original = #"$";
NSString *replacement1 = #"[";
NSString *replacement2 = #"]";
BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
start = !start;
rOriginal = [str rangeOfString: original];
}
NSLog(#"%#", str);
Enjoy Programming!
// string = #"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:#"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
[out appendString:components[i]];
[out appendString: (i % 2) ? #"]" : #"[" ];
}
// out = #"This is a [special markup] sentence."
Try this one
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
if ([string characterAtIndex:i]=='$') {
if (open) {
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"["];
open=!open;
}
else{
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"]"];
open=!open;
}
}
}
NSLog(#"-->%#",string);
Output:
-->This is a message with [specially formatted] content. This is a message with [specially formatted] content

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

How to check whether a string contains white spaces

How to check whether a string contains whitespaces in between characters?
use rangeOfCharactersFromSet:
NSString *foo = #"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
NSLog(#"Found whitespace");
}
note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...
NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
You can also follow these steps:
NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:#" "];
If there is any whitespace in your string, then it will separate those and store different components in the array. Now you need to take the count of array. If count is greater than 1, it means there are two components, i.e, presence of white space.
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(#"Found whitespace");
}

Objective-C: Find consonants in string

I have a string that contains words with consonants and vowels. How can I extract only consonants from the string?
NSString *str = #"consonants.";
Result must be:
cnsnnts
You could make a character set with all the vowels (#"aeiouy")
+ (id)characterSetWithCharactersInString:(NSString *)aString
then use the
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
method.
EDIT: This will only remove vowels at the beginning and end of the string as pointed out in the other post, what you could do instead is use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
then stick the components back together. You may also need to include capitalized versions of the vowels in the set, and if you want to also deal with accents (à á è è ê ì etc...) you'll probably have to include that also.
Unfortunately stringByTrimmingCharactersInSet wont work as it only trim leading and ending characters, but you could try using a regular expression and substitution like this:
[[NSRegularExpression
regularExpressionWithPattern:#"[^bcdefghjklmnpqrstvwx]"
options:NSRegularExpressionCaseInsensitive
error:NULL]
stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""]
You probably want to tune the regex and options for your needs.
Possible, for sure not-optimal, solution. I'm printing intermediate results for your learning. Take care of memory allocation (I didn't care). Hopefully someone will send you a better solution, but you can copy and paste this for the moment.
NSString *test = #"Try to get all consonants";
NSMutableString *found = [[NSMutableString alloc] init];
NSInteger loc = 0;
NSCharacterSet *consonants = [NSCharacterSet characterSetWithCharactersInString:#"bcdfghjklmnpqrstvwxyz"];
while(loc!=NSNotFound && loc<[test length]) {
NSRange r = [[test lowercaseString] rangeOfCharacterFromSet:consonants options:0 range:NSMakeRange(loc, [test length]-loc)];
if(r.location!=NSNotFound) {
NSString *temp = [test substringWithRange:r];
NSLog(#"Range: %# Temp: %#",NSStringFromRange(r), temp);
[found appendString:temp];
loc=r.location+r.length;
} else {
loc=NSNotFound;
}
}
NSLog(#"Found: %#",found);
Here is a NSString category that does the job:
- (NSString *)consonants
{
NSString *result = [NSString stringWithString:self];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"aeiou"];
while(1)
{
NSRange range = [result rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
break;
result = [result stringByReplacingCharactersInRange:range withString:#""];
}
return result;
}

How to remove whitespace in a string?

I have a string say "Allentown, pa"
How to remove the white space in between , and pa using objective c?
This will remove all space from myString.
NSString *newString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
Here is a proper and documented way of removing white spaces from your string.
whitespaceCharacterSet Apple Documentation for iOS says:
Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
+ (id)whitespaceCharacterSet
Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
Discussion
This set doesn’t contain the newline or carriage return characters.
Availability
Available in iOS 2.0 and later.
You can use this documented way:
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps you.
If you need any more help then please let me know on this.
Probably the solution in one of the answers in Collapse sequences of white space into a single character and trim string:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
NSLog(#"Value of the text field is %#",trimmedString);
myStr = [myStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *sample = #" string with whitespaces";
NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
In my case NSString was added Zero Width Space(i i used some library). so solution worked for me.
NSMutableString *newString=[[newString stringByReplacingOccurrencesOfString:#"\u200B" withString:#""] mutableCopy];
#"\u200B" is Zero width space character value.
Here is the proper way to remove extra whitespaces from string which is coming in between.
NSString *yourString = #"Allentown, pa";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:#" "];
you can use remove function to remove any substring from the string
- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input {
return [input stringByReplacingOccurrencesOfString:textToRemove withString:#""];
}
I have tried all the solutions here, none of them could remove the whitespace generated by the Chinese PinYin Input method.
After some debugging, I found this working:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\342\200\206" withString:#""];
I have googled what the '\342\200\206' is, but failed.
Whatever, it works for me.
Hi there is the swift version of the solution with extension :
extension String{
func deleteSpaces() -> String{
return self.stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
And Just call
(yourString as! String).deleteSpaces()
Swift 3:
var word: String = "Hello world"
let removeWhiteSpace = word.stringByRemovingWhitespaces
word = "Helloworld"