Objective-C put string at location of another string - objective-c

I wan't to "know" how to put a string at a location in another string. I already know because I figured out another way to do this. But I wan't to know the real way, does it even exist?
I'm also asking this question for future questions on how to put this string at a location in another string the "false" way (in case it can't be done the real way)
What I mean about putting a (sub)string at a location of string is for example to put
this string:#"Hello" at location:5 inString:#"123456789"
I want the results to be:#"12345Hello6789"
Can this be done the real way? something like this fake code:
[str stringByPuttingString:#"s" atLocation:5];//this code does not exist
I figured out other ways to get this done, can we get it to shorter code?
-(NSString *)putString:(NSString *)str atLocation:(int)location ofString:(NSString *)mainString {
NSRange range = NSMakeRange(location, 0);
return [mainString stringByReplacingCharactersInRange:range withString:str];
}
and
-(NSString *)putString:(NSString *)str atLocation:(int)location ofString:(NSString *)mainString {
NSString *first = [mainString substringToIndex:location];
NSString *last = [mainString substringFromIndex:location];
return [NSString stringWithFormat:#"%#%#%#", first, str, last];
}
The first one feels best, any other ideas or real ideas?
Jonathan,
in future cases of this "problem".

Why not just use an NSMutableString?
NSMutableString *string = [NSMutableString stringWithString:#"123456789"];
[string insertString:#"Hello" atIndex:5];
NSLog(#"%#", string);
Outputs:
12345Hello6789

You can use NSMutableString to accomplish this task. Specifically, see the reference to the insertString:atIndex: method which will do exactly what you want, i.e. insert a string into another string at a specified location. API LINK

you can implement this by using NSMutableString method insertString:atIndex:
Inserts into the receiver the characters of a given string at a given location.
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)anIndex
Parameters
aString
The string to insert into the receiver. aString must not be nil.
anIndex
The location at which aString is inserted. The location must not exceed the bounds of the receiver.
Taken from apple developer classes ref

Related

How to set value of NSString into NSArray

I want to know how to set a value of NSString into NSArray
NSString *holdTheNumberToUpload;
NSArray *resultFetch;
self.resultFetch.count = holdTheNumberToUpload
I used this way:
if (!self.resultFetch.count) {
[self.defaults setObject: [NSString stringWithFormat:#"%lu", (unsigned long)self.resultFetch.count] forKey:#"holdTheNumberToUpload"];
}
You need to use an NSMutableArray instead of a NSArray. It would look like this:
NSString *holdTheNumberToUpload = #"Whatever";
NSMutableArray *resultFetch = [NSMutableArray array];
[resultFetch addObject:holdTheNumberToUpload];
Also, I'm not sure how you're using resultFetch.count. This value is an NSUInteger, so your check if (!resultFetch.count) will never be work because it will always be a non-negative number.
The words you use in your question don't seem to have anything to do with the screen shot. The problem with the code in the screen shot is the expression
[(unsigned long)self.resultFetch.count]
What is that supposed to be? If it's supposed to a number, remove the square brackets. If it's supposed to be an array, put # in front of it:
#[(unsigned long)self.resultFetch.count]
But that won't compile either, because (unsigned long)self.resultFetch.count is not an object. Therefore it cannot be an element of an array, nor can it be the parameter of setObject. Either way, you need to wrap it in an NSNumber, which is an object. Again, you can do this with #:
#self.resultFetch.count
or, if you really insist on the cast to unsigned long,
#((unsigned long)self.resultFetch.count)
So, depending what on earth your code is supposed to mean, you might end up with something like (you want a number?):
#self.resultFetch.count
or something like (you want an array containing a number?):
#[#self.resultFetch.count]

StringByAppendingString function does not work?

NSMutableString *chars=[ [NSMutableString alloc] initWithString:#""] ;
NSString *temp=[[self convertDecimalToChar:(digitizer%10)] copy]; //temp is good
[chars stringByAppendingString:temp]; //chars is empty
Any idea whats wrong here ?
Thank you.
This line:
[chars stringByAppendingString:temp];
Is supossed to return a string combining both strings.
- (NSString *)stringByAppendingString:(NSString *)aString
If you want to just append a string to your string, do this:
[chars appendString:temp];
Find the documentation here:
NSmutableString
The stringByAppendingString method is on the non-mutable NSString class, where non-mutable means you cannot modify it.
Therefore, as with most other NSString methods, it returns a new NSString object, in this case containing the original string plus whatever you passed in the parameter.
However given you are actually manipulating an NSMutableString object, which is mutable, you probably want the appendString: method instead:
[chars appendString:temp];
If you take a look at the documentation of this method, you need to do:
chars = [chars stringByAppendingString:temp];
It is returning a new NSString combining the two NSString, not actually changing the receiver.

Is it necessary to assign a string to a variable before comparing it to another?

I want to compare the value of an NSString to the string "Wrong". Here is my code:
NSString *wrongTxt = [[NSString alloc] initWithFormat:#"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
doSomething;
}
Do I really have to create an NSString for "Wrong"?
Also, can I compare the value of a UILabel's text to a string without assigning the label value to a string?
Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:#"Wrong"]){
//doSomething;
}
Using #"" simply creates a string literal, which is a valid NSString.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}
if ([statusString isEqualToString:#"Wrong"]) {
// do something
}
Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:#"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "#" symbol in a much more convenient way:
NSString *myString = #"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!
You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:#"abc"];
NSString *myString = [NSString stringWithFormat:#"abc %d efg", 42];

What's the best way to trim whitespace from a string in Cocoa Touch?

I'm looking to determine whether a string value from a user input (UITextField) is "blank" if it's not nil. Checking if [textField.text isEqualToString:""] isn't quite enough because I want to avoid any blank/whitespace input (like say a few space characters).
There does seem to be an indication of a good solution for my particular problem in this StOv post.
Basically it goes something like this, but I suspect there has to (or ought to) be a better way:
NSString *strResult;
NSScanner* scanner = [NSScanner scannerWithString:textField.text];
BOOL hasValidChars = [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
intoString:&strResult];
// if hasValidChars == YES, we've got nonwhite space chars collected into strResult
This clearly only works for my particular circumstance, and even then it would fail if the first character was a space but the data I wanted followed. So, I realize I've been a little spoiled by Ruby, but there must be a tried and true idiom for trimming strings in Cocoa.
Aaaand the answer is already out there, my apologies:
NSString's -stringByTrimmingCharactersInSet: would do it:
Returns a new string made by removing
from both ends of the receiver
characters contained in a given
character set.
I'm still curious to hear if anybody has other/preferred ways of doing this.
You're using whitespaceAndNewlineCharacterSet, good. But instead of using scanUpToCharactersFromSet, why not use stringByTrimmingCharactersInSet? Something like this...
strResult = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
EDIT: Didn't realize you already found stringByTrimmingCharactersInSet until after I posted this.
What you are looking for is
[string stringByReplacingOccurrencesOfString:#" " withString:#""].
Deleting white space in the middle of a string is not called 'trimming'.
Trimming by definition works from the edges.
To make this easier on yourself and instead of making a subclass, you can modify existing Apple classes and do something like
//
// NSString+MyExtensions.h
//
#interface NSString (MyExtensions)
- (NSString *)trimmed;
#end
and the implementation
//
// NSString+MyExtensions.m
//
#import "NSString+MyExtensions.h"
#implementation NSString (MyExtensions)
- (NSString *)trimmed {
return [self stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
So now anywhere in your app that you use an NSString, you can now call [#" hello world " trimmed] like below
//
// ViewController.m
//
#import "NSString+MyExtensions.h"
#implementation ViewController
- (void)viewDidLoad {
NSString *string = #" This is a string ";
NSLog(#"The original string: %# \n The trimmed string: %#\n\n",
string,
[string trimmed]);
string = #" ";
if([string trimmed].length == 0)
NSLog(#"%#", #"String is empty! :O");
}
#end
Which would print out
The original string: This is a string
The trimmed string: This is a string
String is empty! :O

Easiest way to concatenate NSString and int

Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSStrings and ints?
[NSString stringWithFormat:#"THIS IS A STRING WITH AN INT: %d", myInt];
That's typically how I do it.
Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.
NSMutableString* aString = [NSMutableString stringWithFormat:#"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:#"... now has another int: %d", myInt];
NSString *s =
[
[NSString alloc]
initWithFormat:#"Concatenate an int %d with a string %#",
12, #"My Concatenated String"
];
I know you're probably looking for a shorter answer, but this is what I would use.
string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.
NSString *string1=#"Hello";
int x=10;
NSString *string2=[string1 stringByAppendingFormat:#"%d ",x];
NSLog(#"string2 is %#",string2);
//NSLog(#"string2 is %#",string2); is used to check the string2 value at console ;
It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.