Appending string to UILabel text? - iphone

I'm starting to develop for the iPhone. I have a beginner-type question, I'm sure:
I have this, which works:
testLabel.text = [NSString stringWithFormat:#"%# to %#", testLabel.text, newLabelText];
I wish I could use the "+=" operator, but I get a compile error (Invalid operands to binary +, have 'struct NSString *' and 'struct NSString *'):
testLabel.text += [NSString stringWithFormat:#"to %#", newLabelText];
Why can't I do this?
Also, how can I shorten my first snippet of code?

You can't use the += operator because C and Objective-C do not allow operator overloading. You're trying to use += with two pointer types, which is not allowed -- if the left-hand side of a += expression has a pointer type, then the right-hand side must be of an integral type, and the result is pointer arithmetic, which is not what you want in this case.

Think about using an NSMutableString - you can use the appendString: method, as in:
NSMutableString *str = [#"hello" mutableCopy];
[str appendString:#" world!"];

That can't be done because ObjectiveC does not support it, ObjectiveC is a small layer over C.
testLabel.text = [testLabel.text stringByAppendingFormat:#" to %#", newLabelText];

NSString are NOT mutable (they can't be changed), that's why you can't use +=.
NSMutableString can be changed. You might be able to use them here.
Your code is already pretty minimal. Objective-C is a expressive language so just get used to long, descriptive function and variable names.

try this:
// usage: label.text += "abc"
public func += (a:inout String?, b:String) {
a = (a ?? "") + b
}
give this custom operator a try:
let label = UILabel()
label.text = "abc"
label.text += "_def"
print(label.text) // “abc_def”

Related

cut nsstring after a special character in iphone

I'm new in iPhone, I want to cut a string after a special character, lets take this example
"works.php" , I want to remove ".php" from this string meaning that I want to remove what's after "."
what is the code to do that ??
thanks in Advance.
It seems you want to use -stringByDeletingPathExtension.
[#"works.php" stringByDeletingPathExtension] // becomes #"works".
Note that this method deletes path extensions, which is not exactly the same as "remove what's after a dot". Please read the reference I've linked above for detail.
If you really just need to remove the string after the last dot, just use the conventional algorithm of (1) find the last dot (2) get a substring until the last dot:
NSString* input = #"works.php";
NSRange lastDotRange = [input rangeOfString:#"." options:NSBackwardsSearch];
if (lastDotRange.location != NSNotFound) {
return [input substringToIndex:lastDotRange.location];
} else {
return input;
}
For the specific example you can use:
- (NSString *)stringByDeletingPathExtension
The more general way to do what you want is:
NSString *originalString = #"works.php";
NSString *finalString =
[[originalString componentsSeparatedByString:#"."] objectAtIndex: 0];
You can replace the dot character with any character you want.
You can use:
myString = #"anything.php";
myString = [myString stringByReplacingOccurrencesOfString:#".php" withString:#""];
The advantage of this is that you can put anything to remove, not only a path. For example:
myString = #"anything-123";
myString = [myString stringByReplacingOccurrencesOfString:#"-123" withString:#""];
Another approach is NSRange and substringWithRange if you want other removing options..

Method to put NSString and NSNumber into array

It's a calculator. I have a display where I can put digits and variables (x, y etc.). When I push Enter button it sends what is on display to array with all operand.
As on display can be NSString (variables) or NSNumber (digits) I thought to use "id" as method argument.
- (IBAction)enterPressed
{
[self.brain pushOperand:self.display.text];
}
/////////////////////
- (void) pushOperand:(id)operand
{
////// So if operand is digit I need to transform it into NSNumber.
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
/////// Here is problem - "Sending '___strong id' to parameter of incompatible type 'double'
NSNumber *digitToStack = [operand doubleValue];
//////// If i do like this, i have warning - "Initializing 'NSNumber *__strong' with an expression of incompatible type 'double'
[self.programStack addObject:operand];
}
I don't understand what this warnings are all about.
So the question is can I somehow put in Array NSNumber and NSString using id method, or how should I do it?
Can i 'transform' argument from 'id' method into NSNumber?
Yes you can "transform" your argument of operand, but you'd need to do a cast.
Also, the line:
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
fails because "operand" is an Objective C object while that function is expecting a C-style double type (which is NOT an Objective C object).
Here's some code I wrote off the top of my head:
// Let's make operand always be a NSString object
// since that's what is being passed in from the label
- (void) pushOperand:(NSString *)operand
{
double doubleValueFromOperand = [operand doubleValue];
if(fabs(doubleValueFromOperand) != HUGE_VAL)
{
NSNumber *digitToStack = [NSNumber numberWithDouble:doubleValueFromOperand];
if(doubleValueFromOperand != 0.0)
{
[self.programStack addObject:digitToStack];
return;
} else {
// because NSString's doubleValue also returns 0.0 for a
// non-numerical string, let's make sure the input from the label
// is not 0.0
if([operand compare: #"0.0" options: NSCaseInsensitiveSearch range: NSMakeRange(0, 3)] == NSOrderedSame)
{
// the operand string *is* a 0.0 input, so let's add it to your stack and return
[self.programStack addObject: digitToStack];
return;
}
}
}
// if we get to this point, we probably have a non-numerical string object
[self.programStack addObject: operand];
}
This code hasn't been tested, has no warranties, and could certainly use a further cleaning up and optimization (e.g. the check for "0.0" isn't what I would put into production code, myself).
But hopefully this is enough to get you further along, Sasha!

Finding element in array

I have the follow code:
NSArray *myArray = [NSArray arrayWithObjects: #"e", #"è", #"é",#"i","ò",nil];
NSString *string = #"simpleè";
NSMutablestring *newString;
for(i=0>;i< [string length]; i++){
if([stringa characterAtIndex:i] is in Array){
[newString appendFormat:#"%c", [string characterAtIndex:i]];
}
}
How make finding if single char of string stay in the array?
Example of result:
newString= #"ieè";
I think you want to apply rangeOfCharacterFromSet:options:range: repeatedly. You'll have to create a NSCharacterSet from the characters in your array somehow.
Added
Though it probably would be just as simple to just loop through the string with characterAtIndex and compare each char (in an inner loop) to the chars in your array (which you could extract into a unichar array or put into a single NSString to make easier to access).
Umm... if you want to check what the values are you can use NSLog
NSLog"%f", myFloat;
So you can use this to check your array... Which is what I think you are asking for, but the grammar in your question isn't very good. Please provide more details and better grammar.
You should check the length of your string and then match your string characters with the array and if found append that character in a new string.
NSString *mstr = #"asdf";
NSString *b = [ mstr characterAtIndex:0];
Hope it helps.......
You'll want to create an NSCharacterSet with the characters in the string and then ask each string in the array for its rangeOfCharacterFromSet:. If you find one where a range was actually found, then a character from the string is in the array. If not, then none of them are.
This might seem a bit roundabout, but Unicode makes looking at strings as just a series of "chars" rather unreliable, and you'll want to let your libraries do as much of the heavy lifting for you as they can.
There are better ways to do this, but this is what I think you're trying to do:
NSMutableString* result= [NSMutableString stringWithString:#""];
for( int i= 0; i < [string length]; ++i ) {
NSString* c= [NSString stringWithFormat:#"%C", [string characterAtIndex:i]];
if( [myArray containsObject:c] )
[result appendString:c];
}

Trouble appendingStrings (NSString) within a method?

when i am using string concatenation in method(like -(IBAction)buttonDigitPressed:(id)sender) it shows the blank.I am recall the method automatically terminate the app. what is the problem plz replay me.
NSString *str= #"";
-(IBAction)buttonDigitPressed:(id)sender{
int a = (int)[sender tag];
str= [str stringByAppendingFormat:#"%i",a];
label1.text= str;
}
this is the code. check the code send me the replay where i am doing the mistake.
str in the method is an autoreleased object. Make it a copy property and do
self.str = [self.str stringByAppendingFormat:#"%i",a];
label1.text = self.str;
If str is same as label1.text then do this directly.
label1.text = [label1.text stringByAppendingFormat:#"%i",a];

How to do a backwards search to find the 2nd space/blank and replace it with another string?

it's me again. I've asked a question similar to this just awhile ago but this question is a bit more complex. I was planning on using RegexKitLite to do what I needed to do but I believe this can be done with out it. I have a NSString that has some words with spaces/blanks in it and I'm wanting to get the very last space in the string that is to the left of the last word. Example String below:
NSString *string = #"Here is an example string HELLO ";
As you can see in the string above there is a space/blank at the very end of the string. I'm wanting to be able to get the space/blank to the left of HELLO and replace it with my own text/string. I'm working on using the NSString's NSBackwardsSearch but it's not working.
NSString *spaceReplacement = #"text that i want";
NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:#" " withString:spaceReplacement];
NSLog(#"%#", replaced);
Any help would help, I'm just tired of trying to fix this thing, it's driving me bonkers. I thought I could do this with RegexKitLite but the learning curve for that is too steep for me considering my timeframe I'm working with. I'm glad Jacob R. referred me to use NSString's methods :-)
This solution assumes you always have a space at the end of your string... it should convert
Here is an example string HELLO
... to:
Here is an example stringtext that i wantHELLO
... since that's what I understood you wanted to do.
Here's the code:
NSString *string = #"Here is an example string HELLO ";
NSRange rangeToSearch = NSMakeRange(0, [string length] - 1); // get a range without the space character
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" " options:NSBackwardsSearch range:rangeToSearch];
NSString *spaceReplacement = #"text that i want";
NSString *result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace withString:spaceReplacement];
The trick is to use the [NSString rangeOfString:options:range:] method.
Note: If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
Disclaimer: I haven't tested the code, but it should compile and work just fine.
Something like this should work:
NSString *string = #"Here is an example string HELLO ";
if ([string hasSuffix:#" "]) {
NSString *spaceReplacement = #"text that i want";
NSString *replacedString = [[string substringToIndex:
[string length]] stringByAppendingString:spaceReplacement];
NSLog(#"replacedString == %#", replacedString);
}
To solve #Senseful note
If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
I had added one line into code that helps in such situations and make code more universal:
// Some income sting
NSString * string = #"Here is an example string HELLO ";
// clear string from whitespace in end on string
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange rangeToSearch = NSMakeRange(0, [string length]);
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" "
options:NSBackwardsSearch
range:rangeToSearch];
// Replaed with String
NSString * spaceReplacement = #"text that i want";
NSString * result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace
withString:spaceReplacement];