Split an NSString to access one particular piece - objective-c

I have a string like this: #"10/04/2011" and I want to save only the "10" in another string. How can I do that?

NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])

Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:#"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

Its working fine
NSString *dateString = #"10/10/2010";//Date
NSArray* dateArray = [dateString componentsSeparatedByString: #"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Objective-c:
NSString *day = [#"10/04/2011" componentsSeparatedByString:#"/"][0];
Swift:
var day: String = "10/04/2011".componentsSeparatedByString("/")[0]

Use [myString componentsSeparatedByString:#"/"]

I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:
///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}

Swift 3.0 version
let arr = yourString.components(separatedBy: "/")
let month = arr[0]

Related

I am getting garbage values while running this code in Xcode using objective c

- (IBAction)btndlr:(id)sender
{
NSString *str =txtdata.text;
lblfinal.text=[NSString stringWithFormat:#"%d/60",(int)str];
}
After running this code without any errors i get garbage value as output in the label.any guidance will be appreciated.thank you.
You must use the NSString method intValue to make it work, try this:
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d/60",[str intValue]];
}
EDIT:
If you want to perform the calculation before writing it out, you should change the last line to:
lblfinal.text = [NSString stringWithFormat:#"%d",[str intValue]/60];
And by the way, if you use division you might want a decimal number as output, then you can write:
lblfinal.text = [NSString stringWithFormat:#"%.2f",[str floatValue]/60];
Hope it helped!
You can't do computations inside format strings. You have to convert the string to an integer with e.g. the intValue property, and perform the computation outside:
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d", str.intValue / 60];
}
Please try this one
- (IBAction)btndlr:(id)sender
{
NSString *str = txtdata.text;
lblfinal.text = [NSString stringWithFormat:#"%d",[str intValue]/60];
}

NSString takes substrings

I have the following NSString in objective C:
[["123"], ["456"], ["adg"]]
and I would like to separate into differents strings like this :
aux = 123;
aux2 = 456;
aux3 = adg;
Please, anyone can help me
Thanks
you can call
NSArray *arrayOfSubStrings = [myString componentsSeparatedByString:#","];
then loop through for each string in the array and remove the square brackets by calling
aux = [stringByReplacingOccurrencesOfString:[arrayOfSubStrings ObjectAtIndex:x] withString:#""]
See NSString Doc for more details
NSString *str = #"[[\"123\"], [\"456\"], [\"adg\"]]";
NSString *new = [[str substringFromIndex:4]substringToIndex:7];
new will be 123
and so on
If you have control over the string format that you're parsing I'd highly recommend looking at JSON and using NSJSONSerialization to parse it. This is more preferable than re-inventing the wheel by defining your own format to store primitive objects.

Finding a substring in a NSString object

I have an NSString object and I want to make a substring from it, by locating a word.
For example, my string is: "The dog ate the cat", I want the program to locate the word "ate" and make a substring that will be "the cat".
Can someone help me out or give me an example?
Thanks,
Sagiftw
NSRange range = [string rangeOfString:#"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *str = #"The dog ate the cat";
NSString *search = #"ate";
NSString *sub = [str substringFromIndex:NSMaxRange([str rangeOfString:search])];
If you want to trim whitespace you can do that separately.
What about this way?
It's nearly the same.
But maybe meaning of NSRange easier to understand for beginners, if it's written this way.
At last, it's the same solution of jtbandes
NSString *szHaystack= #"The dog ate the cat";
NSString *szNeedle= #"ate";
NSRange range = [szHaystack rangeOfString:szNeedle];
NSInteger idx = range.location + range.length;
NSString *szResult = [szHaystack substringFromIndex:idx];
Try this one..
BOOL isValid=[yourString containsString:#"X"];
This method return true or false. If your string contains this character it return true, and otherwise it returns false.
NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:#"Ur String"].location];
You can search for a string and then get the searched string into another string...
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm options:NSCaseInsensitiveSearch].location==NSNotFound?FALSE:TRUE;
}
You can use any of the two methods provided in NSString class, like substringToIndex: and substringFromIndex:. Pass a NSRange to it as your length and location, and you will have the desired output.

stringByAppendingFormat not working

I have an NSString and fail to apply the following statement:
NSString *myString = #"some text";
[myString stringByAppendingFormat:#"some text = %d", 3];
no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString.
any clues most welcome.
I would suggest correcting to (documentation):
NSString *myString = #"some text";
myString = [myString stringByAppendingFormat:#" = %d", 3];
From the docs:
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
It's working, you're just ignoring the return value, which is the string with the appended format. (See the docs.) You can't modify an NSString — to modify an NSMutableString, use -appendFormat: instead.
Of course, in your toy example, you could shorten it to this:
NSString *myString = [NSString stringWithFormat:#"some text = %d", 3];
However, it's likely that you need to append a format string to an existing string created elsewhere. In that case, and particularly if you're appending multiple parts, it's good to think about and balance the pros and cons of using a mutable string or several immutable, autoreleased strings.
Creating strings with #"" always results in immutable strings. If you want to create a new NSMutableString do it as following.
NSMutableString *myString = [NSMutableString stringWithString:#"some text"];
[myString appendFormat:#"some text = %d", 3];
I had a similar warning message while appending a localized string. This is how I resolved it
NSString *msgBody = [msgBody stringByAppendingFormat:#"%#",NSLocalizedString(#"LOCALSTRINGMSG",#"Message Body")];

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];