Uppercase first letter in NSString - iphone

How can I uppercase the fisrt letter of a NSString, and removing any accents ?
For instance, Àlter, Alter, alter should become Alter.
But, /lter, )lter, :lter should remains the same, as the first character is not a letter.

Please Do NOT use this method. Because one letter may have different count in different language. You can check dreamlax answer for that. But I'm sure that You would learn something from my answer.
NSString *capitalisedSentence = nil;
//Does the string live in memory and does it have at least one letter?
if (yourString && yourString.length > 0) {
// Yes, it does.
capitalisedSentence = [yourString stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[yourString substringToIndex:1] capitalizedString]];
} else {
// No, it doesn't.
}
Why should I care about the number of letters?
If you try to access (e.g NSMakeRange, substringToIndex etc)
the first character in an empty string like #"", then your app will crash. To avoid this you must verify that it exists before processing on it.
What if my string was nil?
Mr.Nil: I'm 'nil'. I can digest anything that you send to me. I won't allow your app to crash all by itself. ;)
nil will observe any method call you send to it.
So it will digest anything you try on it, nil is your friend.

You can use NSString's:
- (NSString *)capitalizedString
or (iOS 6.0 and above):
- (NSString *)capitalizedStringWithLocale:(NSLocale *)locale

Since you want to remove diacritic marks, you could use this method in combination with the common string manipulating methods, like this:
/* create a locale where diacritic marks are not considered important, e.g. US English */
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en-US"] autorelease];
NSString *input = #"Àlter";
/* get first char */
NSString *firstChar = [input substringToIndex:1];
/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:locale];
/* create the new string */
NSString *result = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];

Gonna drop a list of steps which I think you can use to get this done. Hope you can follow through without a prob! :)
Use decomposedStringWithCanonicalMappingto decompose any accents (Important to make sure accented characters aren't just removed unnecessarily)
Use characterAtIndex: to extract the first letter (index 0), use upperCaseString to turn it into capitol lettering and use stringByReplacingCharactersInRange to replace the first letter back into the original string.
In this step, BEFORE turning it into uppercase, you can check whether the first letter is one of the characters you do not want to replace, e.g. ":" or ";", and if it is, do not follow through with the rest of the procedure.
Do a [theString stringByReplacingOccurrencesOfString:#"" withString:#""]` sort of call to remove any accents left over.
This all should both capitalize your first letter AND remove any accents :)

Since iOS 9.0 there is a method to capitalize string using current locale:
#property(readonly, copy) NSString *localizedCapitalizedString;

I'm using this method for similar situations but I'm not sure if question asked to make other letters lowercase.
- (NSString *)capitalizedOnlyFirstLetter {
if (self.length < 1) {
return #"";
}
else if (self.length == 1) {
return [self capitalizedString];
}
else {
NSString *firstChar = [self substringToIndex:1];
NSString *otherChars = [self substringWithRange:NSMakeRange(1, self.length - 1)];
return [NSString stringWithFormat:#"%#%#", [firstChar uppercaseString], [otherChars lowercaseString]];
}
}

Just for adding some options, I use this category to capitalize the first letter of a NSString.
#interface NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst;
- (NSString *)removeDiacritic;
#end
#implementation NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst {
if ( self.length <= 1 ) {
return [self uppercaseString];
}
else {
return [[[[self substringToIndex:1] removeDiacritic] uppercaseString] stringByAppendingString:[[self substringFromIndex:1] removeDiacritic]];
// Or: return [NSString stringWithFormat:#"%#%#", [[[self substringToIndex:1] removeDiacritic] uppercaseString], [[self substringFromIndex:1] removeDiacritic]];
}
}
- (NSString *)removeDiacritic { // Taken from: http://stackoverflow.com/a/10932536/1986221
NSData *data = [NSData dataUsingEncoding:NSASCIIStringEncoding
allowsLossyConversion:YES];
return [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
}
#end
And then you can simply call:
NSString *helloWorld = #"hello world";
NSString *capitalized = [helloWorld capitalizeFirst];
NSLog(#"%# - %#", helloWorld, capitalized);

Related

Get first sentence of textview

I am trying to get the first sentence of a text view. I have the following code but am getting an out of bounds error. Thank You. Or are there any ways that aren't really complex.
-(IBAction)next:(id)sender
{
NSRange ran = [[tv.text substringFromIndex:lastLocation] rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * getRidOfFirstHalfString = [[tv.text substringFromIndex:lastLocation] substringToIndex:ran.location];
NSLog(#"%#",getRidOfFirstHalfString);
lastLocation+=getRidOfFirstHalfString.length;
}
How about:
NSString *finalString = [[tv.text componentsSeparatedByString:#"."] objectAtIndex:0] // Get the 1st part (left part) of the separated string
Go through the textview's text and divide the text into separate components where you find a period by calling componentsSeperatedByString on tv.text. You want the first sentence, which would be the 0th object in the array.
I know you've already accepted an answer to this question, but you might want to consider using the text view's tokenizer instead of just searching for the string ". " The tokenizer will automatically handle punctuation like !, ?, and closing quotes. You can use it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextRange *range = [tokenizer rangeEnclosingPosition:textView.beginningOfDocument
withGranularity:UITextGranularitySentence
inDirection:UITextStorageDirectionForward];
NSString *firstSentence = [textView textInRange:range];
If you want to enumerate all of the sentences, you can do it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *start = textView.beginningOfDocument;
while (![start isEqual:textView.endOfDocument]) {
UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularitySentence inDirection:UITextStorageDirectionForward];
NSString *sentence = [textView textInRange:[textView textRangeFromPosition:start toPosition:end]];
NSLog(#"sentence=%#", sentence);
start = end;
}
Try checking that the substring was actually found.
NSRange ran = [tv.text rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * selectedString = [tv.text substringToIndex:ran.location];
NSLog(#"%#",selectedString);
}
You could alternatively try using NSScanner like this:
NSString *firstSentence = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:tv.text];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"."];
[scanner scanUpToCharactersFromSet:set intoString:&firstSentence];
I'm not sure if you want this, but since you want the first sentence, you could append a period (you probably know how to do this, but it doesn't hurt to show it anyway):
firstSentence = [firstSentence stringByAppendingFormat:#"."];
Hope this helps!
PS: If it didn't work for you, maybe the text view doesn't actually contain any text.

Deleting a number digit by digit on a calculator screen

I want to delete a number digit by digit on the calculator screen but am only being able to delete the full number . Is there any method ?
-(IBAction)cancelInput:(float)result1{
NSString *myString = [[NSNumber numberWithFloat:result] stringValue];
int str=[myString length]-1;
NSString *newstring = [[NSNumber numberWithInt:str] stringValue];
calculatorScreen.text= [NSString stringWithFormat:newstring];
//NSLog(#"%d ",str);
}
Here you go,
NSString *myString = [[NSNumber numberWithFloat:result] stringValue];
myString = [myString substringToIndex:[myString length]-1];
calculatorScreen.text= myString;
int str=[myString length]-1 will only return the length of your string, say if your number is 9876, it will return 3(4-1) and your newstring will be 3.If you want to delete the last character you have to create substring of myString.
string = [string substringToIndex:[string length] - 1];
-(IBAction)backPressed:(UIButton *)sender
{
self.display.text=[self.display.text substringToIndex:[self.display.text length]-1];
if ( [self.display.text isEqualToString:#""] || [self.display.text isEqualToString:#"-"])
{
self.display.text =#"0";
}
}
This is the core function for the button. I took the liberty to add in the if feature so that it could handle some of the basic issues. As usual, replace display with your primary label. The If function help to counter check that your label does not become empty " " or have a negative sign "-" and will automatically replace it with "0", similar to clear in that aspect. in which you can run the clear method instead. But use
self.display.text =#"0";
for better clarification instead.
Use this code for it:
else if([character isEqualToString:(NSString*) Delete])
{
NSInteger index_of_char_to_remove=[_display length]-1;
if(index_of_char_to_remove>=0)
{
[_display deleteCharactersInRange:NSMakeRange(index_of_char_to_remove, 1)];
last_character_is_operator=NO;
}
}
When press 'C' it will checked this condition and delete the data one by one

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;
}

Any Way To Separate Text In UITextField?

I have a paragraph (4 sentences) of text in an .plist array that loads into a UITextView.
By default, it presents the text how it is, as one big lump of text in a paragraph. I want to know if it is possible to split this up?
Such as Line 1: sdfafasfsafsa, then line 2: asfdsafs, line 3: adfsfsdfsdfa, etc.
Is there a way I can search for a . and then separate the lines accordingly? I would just edit the plist manually but there are hundreds of entries so it isn't easy to do.
NSString* tidiedString = [sourceString stringByReplacingOccurrencesOfString:#"." withString:#"\n"];
Update: OK, so more detail is coming through. You could use a regular expression - but if you're not familiar, the learning curve is a bit steep. Otherwise, as with other answers, crank through the list. You need to take care of whitespaces, empty lines etc. The following snippet isn't pretty, but will do the job.
NSString* sourceString = #"Hyperlinks can be great. They can also dilute your focus and tempt you into putting off what you most want to do. Here I chose to place links at the foot of the page to help you to make an active choice as to whether to surf or refocus your attention elsewhere.";
NSArray* arrayOfStrings = [sourceString componentsSeparatedByString:#"."];
NSMutableString* superString = [NSMutableString stringWithString:#""];
int lineCount = 1;
for (NSString* string in arrayOfStrings)
{
if ([string length] < 1) continue;
[superString appendFormat:#"Line %d: %#.\n", lineCount++, [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
[superString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[[self userEntry] setText:superString];
NSArray *array = [sourceString componentsSeparatedByString:#"."];
NSMutableString *resultString= [[NSMutableString alloc] init];
int linecount=1;
for(NSString *lines in array)
{
[resultString appendString:[NSString stringWithFormat:#"Line%i:%#\n",linecount++,lines]];
}
NSLog(#"resultString:%#",resultString);
this may help..!!
Try making a loop that runs through the array and that adds every line to the UITextView plus #"\n".
So something like...:
NSString *curText = txtView.text;
NSString *lineBreak = #"\n";
txtView.text=[NSString stringWithFormat:#"%# + %#", curText, lineBreak];
Or just replace the dots by #"\n".

iPhone - Check if character is capital

Hey! I was wondering if there was any way to check if the first letter of a string was capital or not in an NSString. Something similar to:
if ([[string substringToIndex:1] isCapitalLetter]) {
// CODE
}
--or--
if ([self isCapitalLetter:[string substringToIndex:1]]) {
// CODE
}
[[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[myString characterAtIndex:0]];
The only thing I can think of would be to do something like this:
// get the first character, capitalized
NSString *capital = [[oldstring substringToIndex:1] capitalizedString];
// then compare to your oldstring
if ( [[oldstring substringToIndex:1] isEqualToString:capital] ) {
// do stuff...
}
The NSString reference is your friend: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html