iOS Beginner: String concatenation - iphone

I've concatenated string using the following code:
NSString *add = #"a ";
lbl.text = [add stringByAppendingString:lbl.text];
Which adds 'a ' to lbl variable every time I call the function.
But for some reason this method concatenates in a way that the new string adds in the beginning of what's already there, and not to the end.
Instead of getting AAABBB, I get BBBAAA. How do I fix this?

If a = AAA and b = BBB then you will need to write
[a stringByAppendingString:b];
So in your case it will be
[lbl.text stringByAppendingString:add]; as lbl.text = AAA and add = BBB.
For more information about this method please see NSString documentation.

NSMutableString *aString = [NSMutableString stringWithString:#"AAA"];
NSMutableString *bString = [NSMutableString stringWithString:#"BBB"];
[aString appendString:bString];
NSLog(#"Astring:%#",aString);

You can also use NSMutableString. Declare an NSMutableString *s, and then call [s appendString:..], or you can also call [s appendFormat:[NSString stringWithFormat:#"",];

Related

How to replace two different strings in iPhone programming

I am reading CSV file in my application.
I want to replace two different strings and print as one line. for example:
string1#$string2#$string3####string4
I want to replace #$ with , and #### with \n
and want to show the result on a UILabel.
You can use stringByReplacingOccurrencesOfString:withString: method, like this:
NSString *orig = "string1#$string2#$string3####string4";
NSString *res = [orig stringByReplacingOccurrencesOfString:#"#$" withString:#" "];
res = [res stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
Note that the original string does not get changed: instead, a new instance is produced with the replacements that you requested.
use
String = [String stringByReplacingOccurrencesOfString:#"#$" withString:#","];
String = [String stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
And then
yourLabel.text=String;
Try this
NSString *string = #"####abc#$de";
string = [string stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
string = [string stringByReplacingOccurrencesOfString:#"#$" withString:#","];
Hope it helps you

In the iPhone SDK is it safe and proper to chain stringByAppendingString in line?

Is there a better way to achieve concatenating multiple strings in one single line? Or any advise at all when doing this.
NSString *string1 = #"one";
NSString *string2 = #"one";
NSString *string3 = #"one";
NSString *appendedText = #"";
[appendedText = [[string1 stringByAppendingString: string2] stringByAppendingString: string3]
Safe and proper? Sure.
Let's say you have:
NSString *a = #"hay";
NSString *b = #"bee";
NSString *c = #"see";
You can use stringByAppendingString: to concatenate them all:
cat = [a stringByAppendingString:[b stringByAppendingString:c]];
You can use stringByAppendingFormat: to concatenate them all:
cat = [a stringByAppendingFormat:#"%#%#", b, c];
You can use stringWithFormat::
cat = [NSString stringWithFormat:#"%#%#%#", a, b, c];
You can put them in an array, and use componentsJoinedByString::
(just for fun, using array literal syntax)
array = #[ a, b, c];
cat = [array componentsJoinedByString:#""];
You can collect them in a mutable string:
NSMutableString *temp = [a mutableCopy];
[temp appendString:b];
[temp appendString:b];
cat = [temp copy]; // if you want to make sure result is immutable
All of these methods are OK. Here's my advice for choosing one to use:
Use whichever one makes your code clear and easy to read.
When your app is working correctly, use Instruments to profile it.
Only if you find out that string concatenation is causing a performance problem, consider a different method.
You can use stringByAppendingFormat:
[string1 stringByAppendingFormat:#"%#%#",string2,string3]
Here is a ref
you also have NSMutableString but in terms of syntax it will look about the same
Daniel

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.

append in middle of NSString in iPhone programming

how to append the value of string in between NSString?
for example:
NSString* str1 = #"Hello";
NSString* str2 = #"Hi.."/*add contents of str1*/#"how r u??";
please tell me how to achieve this??
There are multiple answers possible. It depends a bit on how you want to figure out where to insert the text. One possibility is:
NSString *outStr = [NSString stringWithFormat:"%#%#%#", [str2 substringToIndex:?], str1, [str2 substringFromIndex:?]];
(Append always means add to the end. That's inserting a string in the middle.)
If you simply want to construct a literal string, use
#define STR1 #"Hello"
NSString* str2 = #"Hi..." STR1 #" how r u??";
To insert it in run time you need to convert str2 into a mutable string and call -insertString:atIndex:.
NSMutableString* mstr2 = [str2 mutableCopy];
[mstr2 insertString:str1 atIndex:4];
return [mstr2 autorelease];

Strings in Objective C for Iphone

i am new to iphone application development.
i have a string say abc, i just want to display it as "Hello abc" in the screen
i want to add Hello to abc , before abc.
In objective c, i saw functions appendString , which displays result as "abc Hello"
But i want to display i as "Hello abc"
The easiest way to do it is:
NString *myString = #"abc";
NSString *finalString = [NSString stringWithFormat:#"Hello %#", myString];
NSLog(#"%#", finalString);
this will output "Hello abc".
I say that this is the easiest way, beacause you can reuse this method to add more stuff to the string, like a number:
NSString *playerName = #"Joe";
int num = 5;
[NSString stringWithFormat:#"%# scored %d goals.", playerName, 5];
Try do this:
NSString *string1 = #"abc";
NSString *string2 = [NSString stringWithFormat:#"Hello %#", string1];
You dont need to re-declare the NString variables you can do it via single Mutable variable like.....
NSMutableString *myStr = [NSMutableString string];
[myStr appendString:#"Hello"];
[myStr appendString:#" Cloud"];
int num = 9;
[myStr appendFormat:#" Number %i",num];
NSLog(#"%#",myStr);
and this will print "Hello Cloud Number 9".
Hope this helps.