iOS: Create String from Variable and string combined - ios

I need to concatenate a string and a variable together - I kind of find lots of examples of adding a string prior to a variable but not the other way round - how do I do this?
NSString *theImage = [[self.detailItem valueForKey:#" resimagefiletitle"] description], #"'add on the end";

Something like this:
NSString *theImage = [NSString stringWithFormat:#"%# %#",[self.detailItem valueForKey:#" resimagefiletitle"], #"'add on the end"];
Or:
NSString *theImage = [NSString stringWithFormat:#"%# add on the end",[self.detailItem valueForKey:#" resimagefiletitle"]];

Try this
NSString *theImage = [NSString stringWithFormat:#"%# '>",[[self.detailItem valueForKey:#"resimagefiletitle"] description]];
Here I am considering [[self.detailItem valueForKey:#"resimagefiletitle"] description] gives NSString

We can concat diffrent type of datatypes into string by mention the format for it.
like if your want to concat two or more strings together then you can use the following code:
NSString *NewString = [NSString stringWithFormat:#"%#%#",#"This Is",#"way to concate string"];
and if your want concat integer value then you can mention the data format for it "%i".
eg:
int OutOf = 150;
NSString *NewString = [NSString stringWithFormat:#"%#%i",#"I got 100 out of ",OutOf];
this may help you.

Related

iphone - app crash in a form

In my app, I have a view where user have to fill a form. But, sometime the app crash here, in this function, that simple cacth the value field and built a url to give
-(NSString*)urlToUpload{
NSString *string1 =[[NSString alloc]init];
string1= [NSString stringWithFormat:#"?nombre="];
NSString *string2 = [string1 stringByAppendingString:nameAdded];
//crash here
NSString *string3 = [string2 stringByAppendingString:#"&horario="];
NSString *string4 = [string3 stringByAppendingString:horarioAdded];
NSString *string5 = [string4 stringByAppendingString:#"&info="];
NSString *string6 = [string5 stringByAppendingString:infoAdded];
NSString *string7 = [string6 stringByAppendingString:#"&offerta="];
NSString *string8 = [string7 stringByAppendingString:offertaAdded];
NSString *lat_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.latitude] autorelease];
NSString *lon_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.longitude] autorelease];
NSString *string9 = [string8 stringByAppendingString:#"&latitude="];
NSString *string10 = [string9 stringByAppendingString:lat_string];
NSString *string11 = [string10 stringByAppendingString:#"&longitude="];
NSString *string12 = [string11 stringByAppendingString:lon_string];
NSString *url1 = [NSString stringWithFormat:#"http://myserverside/mysql_up.php"];
NSString *url = [url1 stringByAppendingString:string12];
return url;
}
EDIT:
It seems problem appers on nameAdded when there is a white space into textField(i.e. MisterB not crash, Mister B yes ).
But I am using:
nameAdded =[[nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and NSLOg give of nameAdded is Mister%20B.
The crash still appearing...
Just use a single stringWithFormat::
- (NSString *)urlToUpload {
NSString *url = [NSString stringWithFormat:#"http://myserverside/mysql_up.php?nombre=%#&horario=%#&info=%#&offerta=%#&latitude=%f&longitude=%f",
[nameAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[horarioAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[infoAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[offertaAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
locationToUpload2.latitude, locationToUpload2.longitude];
return url;
}
Make sure the referenced variables are valid.
In your original code there is no need to alloc/init an NSString then assign another string to the same variable. That's a memory leak (string1).
If you really want to structure your code the way you have it, at least use an NSMutableString and append to that one mutable string. Creating over a dozen NSString variables is the wrong way to do it.
Updated: Ensure each of the strings added to the URL are properly escaped.
It looks like nameAdded may be the cause of your problems. Is it nil at that point?
Also
You are allocating a string, setting it to string1 and then immediately setting string1 to the class function stringWithFormat which allocates another string. Also you are using stringWithFormat but you aren't using any format so you could simply use NSString *string1 = #"?nombre=";
Rather than declaring all of those variables you should just use NSMutableString and build it all in one variabl

How to concatenate TextView.text

I have two UITextViews:
self.itemsTextView.text;
self.priceTextView.text;
I want to concatenate these two like so:
NSString *data = self.textView.text + self.itemsTextView.text;
I have tried using a colon, as suggested by this thread, but it doesn't work.
NSString *data = [self.textView.text : self.itemsTextView.text];
For concatenating you have several options :
Using stringWithFormat:
NSString *dataString =[NSString stringWithFormat:#"%#%#",self.textView.text, self.itemsTextView.text];
Using stringByAppendingString:
NSMutableString has appendString:
You may use
NSString * data = [NSString stringWithFormat:#"%#%#",self.textView.text,self.itemsTextView.text];
There are so many ways to do this. In addition to the stringWithFormat: approaches of the other answers you can do (where a and b are other strings):
NSString *c = [a stringByAppendingString:b];
or
NSMutableString *c = [a mutableCopy];
[c appendString b];

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

Inserting a string into another string

I am working on iPhone app. I have the SQL query:
NSString *myRed = [NSString stringWithFormat: #"%1.4f", slideR.value];
[self insertData:#"INSERT INTO colour VALUES("+myRed+")"];
It produces syntax error. How to insert a string into string. That approach in Java would have worked.
Best regards
Try this :
NSString *myRed = [NSString stringWithFormat: #"%1.4f", slideR.value];
[self insertData:[NSString stringWithFormat:#"INSERT INTO colour VALUES(\"%#\")",myRed]];
If you don't want " then :-
[self insertData:[NSString stringWithFormat:#"INSERT INTO colour VALUES(%#)",myRed]];
Hope it helps you.
You could try writing your query and your string appended together before hand.
NSString *str = #"Your values";
NSString *query = [NSString stringWithFormat:#"INSERT INTO color VALUES(%#)", str];
[self insertData:query];

Convert float to NSString using custom format? ("xx:yy")

I'm getting a JSON string back from a web service I'm using, one of the items is a float, which is formatted like this: "1.2".
But I actually want to make it show like a time number, so like this: "01:20".
What would be the easiest way of doing this?
I thought about converting the float to a string and then splitting it into 2 pieces
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
NSArray *tmpArr = [timeValue componentsSeparatedByString:#"."];
NSString *tmpFirst = (NSString *)[tmpArr objectAtIndex:0];
NSString *tmpSecond = (NSString *)[tmpArr objectAtIndex:0];
But somehow when I convert it, it returns me a negative number
NSLog(#"timeValue: %#", timeValue);
timeValue: -1.99
I think the problem is in this line.
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
I think timeValue is of type NSString if not then why are you using same variable twice.
It should be like
timeValueString = [NSString stringWithFormat:#"%.2f", timeValueFloat];

Resources