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
Related
I'm currently using this HTAutocompleteTextField to fill in a UITextField with a predefined list, should A user start typing in an entry that already exists. There are a couple of problems that I've been having however. The first is that it seems to stop when a comma is typed in (but not apostrophes). I've been looking around and I'm really not sure why it's doing it. I thought at one point it could be that the comma was a different comma, like an apostrophe issue I had due to importing the list from a word document. However, it wasn't the case. The second issue is more of an addition which I'm not really sure how to implement. I also want the autosuggest to detect suggestions for words in mid string, not just from the beginning. So for instance typing in "String" would suggest "This is a String". This currently how it does the auto suggest, but I have no idea how to do the above things.
NSString *prefixLastComponent = [componentsString.lastObject stringByTrimmingCharactersInSet:space];
if (ignoreCase)
{
stringToLookFor = [prefixLastComponent lowercaseString];
}
else
{
stringToLookFor = prefixLastComponent;
}
for (NSString *stringFromReference in colorAutocompleteArray)
{
NSString *stringToCompare;
if (ignoreCase)
{
stringToCompare = [stringFromReference lowercaseString];
}
else
{
stringToCompare = stringFromReference;
}
if ([stringToCompare hasPrefix:stringToLookFor])
{
return [stringFromReference stringByReplacingCharactersInRange:[stringToCompare rangeOfString:stringToLookFor] withString:#""];
}
}
If anyone could give me any pointers on how to get this done, I'd appreciate it.
Regards,
Mike
Managed to go about solving both issues. For any one who uses this Git Repository, the reason why commas don't work when using the preset methods is because of NSArray *componentsString = [prefix componentsSeparatedByString:#","];. Remove the comma so it's NSArray *componentsString = [prefix componentsSeparatedByString:#""]; and it should work nicely. To fix the other problem where it only detects the start of words, I changed the methods a little. Here are my changes in HTAutocompleteManager.m
int i = 0;
for (NSString *stringFromReference in colorAutocompleteArray)
{
NSString *stringToCompare;
if (ignoreCase)
{
stringToCompare = [stringFromReference lowercaseString];
}
else
{
stringToCompare = stringFromReference;
}
if ([stringToCompare hasPrefix:stringToLookFor])
{
//NSLog(#"Removing String: %# atIndex: %d", [colorAutocompleteArray objectAtIndex:i], i);
[colorAutocompleteArray removeObjectAtIndex:i];
[colorAutocompleteArray insertObject:stringFromReference atIndex:0];
//NSLog(#"Adding String atIndex 0: %#", stringFromReference);
return [stringFromReference stringByReplacingCharactersInRange:[stringToCompare rangeOfString:stringToLookFor] withString:#""];
}
else if ([stringToCompare hasSuffix:stringToLookFor] && ([stringToLookFor length] >= 3)) {
return [NSString stringWithFormat:#" %#", stringFromReference];
}
else if (!([stringToCompare rangeOfString:stringToLookFor].location == NSNotFound) && ([stringToLookFor length] >= 3))
{
return [NSString stringWithFormat:#" %#", stringFromReference];
}
++i;
}
The reason for reordering the Array is because after the 3rd character is typed it will prioritise the other two if statements because they will be reached first if there is a generic term in multiple entries in the array (like "Street" in a list of locations). I know it's not necessary to have the "hasSuffix" if statement, but I left it in case someone wants to use it on it's own. Lastly, I added in a space before stringFromReference so that it doesn't look weird when there's a suggestion straight after the input text. When we exit the UITextField we remove this space like this (inside HTAutocompleteTextField.m - commitAutocompleteText):
NSString *currentText = self.text;
if ([self.autocompleteString isEqualToString:#""] == NO
&& self.autocompleteDisabled == NO)
{
if ([self.autocompleteString hasPrefix:#" "]) {
self.autocompleteString = [self.autocompleteString substringFromIndex:1];
}
self.text = [NSString stringWithFormat:#"%#", self.autocompleteString];
self.autocompleteString = #"";
[self updateAutocompleteLabel];
}
return ![currentText isEqualToString:self.text];
Hope this makes sense to anyone who's in a similar situation.
Mike
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 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);
when i convert my array by following method , it adds () charracter.
i want to remove the () how can i do it..
NSMutableArray *rowsToBeDeleted = [[NSMutableArray alloc] init];
NSString *postString =
[NSString stringWithFormat:#"%#",
rowsToBeDeleted];
int index = 0;
for (NSNumber *rowSelected in selectedArray)
{
if ([rowSelected boolValue])
{
profileName = [appDelegate.archivedItemsList objectAtIndex:index];
NSString *res = [NSString stringWithFormat:#"%d",profileName.userID];
[rowsToBeDeleted addObject:res];
}
index++;
}
UPDATE - 1
when i print my array it shows like this
(
70,
71,
72
)
Here's a brief example of deleting the given characters from a string.
NSString *someString = #"(whatever)";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSMutableString *mutableCopy = [NSMutableString stringWithString:someString];
NSRange range;
for (range = [mutableCopy rangeOfCharacterFromSet:charSet];
range.location != NSNotFound;
[mutableCopy deleteCharactersInRange:range],
range = [mutableCopy rangeOfCharacterFromSet:charSet]);
All this does is get a mutable copy of the string, set up a character set with any and all characters to be stripped from the string, and find and remove each instance of those characters from the mutable copy. This might not be the cleanest way to do it (I don't know what the cleanest is) - obviously, you have the option of doing it Ziminji's way as well. Also, I abused a for loop for the hell of it. Anyway, that deletes some characters from a string and is pretty simple.
Try using NSArray’s componentsJoinedByString method to convert your array to a string:
[rowsToBeDeleted componentsJoinedByString:#", "];
The reason you are getting the parenthesis is because you are calling the toString method on the NSArray class. Therefore, it sounds like you just want to substring the resulting string. To do this, you can use a function like the following:
+ (NSString *) extractString: (NSString *)string prefix: (NSString *)prefix suffix: (NSString *)suffix {
int strLength = [string length];
int begIndex = [prefix length];
int endIndex = strLength - (begIndex + [suffix length]);
if (endIndex > 0) {
string = [string substringWithRange: NSMakeRange(begIndex, endIndex)];
}
return string;
}
I Spent 5 hours try to figure a way for that..i'm trying to do a hangman app for iphone and the method below is the method that should be called when the player chooses a character and it match the chosen word..
-(void)replaceTheHiddenTextWithNewText:(NSString*)character{
NSString *fullTextField = fullText.text;
int textCount = [hiddenText.text length];
NSString *theRiddle;
for (int i = textCount-1 ; i>=0; i--) {
NSString *hiddenTextField = [[NSMutableString alloc] initWithString:hiddenText.text];
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i/3,1)];
if ([aChar isEqualToString:#" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}else{
theRiddle = [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#"_"];
}
hiddenTextField = theRiddle;
}
hiddenText.text=theRiddle;
}
the problem is stringByReplacingCharactersInRange doesn't replace the character, it appends it to the underscore what am I doing wrong here?
Best Regards,
M Hegab
Just played around with your code. It does not work, but stringByReplacingCharactersInRange is not your problem.
Your game logic doesn't work like it should. Get a pen and a sheet of paper and "manually" loop through your for loop to see that this must be wrong.
Next time, if you've stared at code for half an hour, take a pen. This will save you at least 4 hours :-)
There are some issues with your code. Assume Kartoffelkäfer is the word you are looking for, and the user enters the letter f.
for (int i = textCount-1 ; i>=0; i--) {
NSString *hiddenTextField = [[NSMutableString alloc] initWithString:hiddenText.text];
// you are creating this string in every loop from the text of a (I guess) UITextField.
// I don't know what the content of this text is but I guess it is suppossed to be `______________`
// in every loop you replace the word where you replaced the _ with the correct letter with the string from the textfield.
// Btw, you are leaking this string.
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i/3,1)];
// Kartoffelkäfer has 14 chars so i is 13. And 13/3 is 4. And the character at index 4 is o
// In the next loop i is 12. And 12/3 is 4, too.
// next three loops will give you index 3. Then you get three times index 2, and so one.
// you never reach the letter f, anyway.
if ([aChar isEqualToString:#" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}else{
theRiddle = [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#"_"];
// You should not replace a unmatched character with a _ . Because already matched letters would be overwritten.
}
hiddenTextField = theRiddle;
}
I assumed that the content of hiddenText.text is #"______"
and the content of fullText.text is #"Kartoffelkäfer". So hiddentext is the exact length as the fullText.
What I had to change to get this to work:
NSString *theRiddle;
NSString *hiddenTextField = [[[NSMutableString alloc] initWithString:hiddenText.text] autorelease];
for (int i = textCount-1 ; i>=0; i--) {
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i,1)];
if ([aChar isEqualToString:#" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}
else {
theRiddle = hiddenTextField;
}
hiddenTextField = theRiddle;
}
hiddenText.text=theRiddle;
Far away from good code, but I tried to change your code as little as possible.