I am confused about strings (a beginner's problem, I'm afraid):
I have one NSMutableArray called Notebook. At index position 1, I have an object, which I think is a string. At least I put it into the array like this:
[NoteBook replaceObjectAtIndex:1 withObject:#"x-x-x-x"];
So far so good. If I put this into an UILabel, it will show x-x-x-x on my screen. The nightmare starts when I try to compare this string with other strings. Let's consider that I do not want to display the string x-x-x-x on my screen, but just to have a blank instead. So I thought I could achieve this by coding this:
NSString *tempDateString;
tempDateString = [NSString stringWithFormat:#"%#",[NoteBook objectAtIndex:1]];
if (tempDateString == #"x-x-x-x") {
UISampleLabel.text = #"";
}
For some reason, this does not work, i.e. even if the string at position 1 of my array is 'x-x-x-x', it will still not set my UISampleLabel to nothing.
I suppose that I am getting confused with the #"" markers. When do I really need them? Why can't I simply code tempDateString = [NoteBook objectAtIndex:1]; without the formatting thing?
Any help and suggestions would be very much appreciated!
You need to compare string with isEqualToString:
if ([tempDateString isEqualToString:#"x-x-x-x"]) {
UISampleLabel.text = #"";
}
In addition to the question that's been answered:
Why can't I simply code tempDateString = [NoteBook objectAtIndex:1]; without the formatting thing?
You can. Why do you think you can't?
Related
this is hard to describe but I am currently catching a string from a database, this string can be 1-4 characters long, however I am wanting to always display 4 characters, so if i get say a string back that is 34, i want it to be 0034.
I have set up a method to catch the string so now I just need to figure out how to do this. what I then plan to do is feed that string into a NSArray so I can send each [i'th] of the array off to 4 differetn methods that control animations in my app.
The reason its in string format is because I have had to bounce it round from hex, to int to string for various formatting reasons within the application.
this is my code i have so far. Suggestions/solutions would be great thankyou, I am so new its hard to find solutions for stuff like string manipulation etc..
//... other method I am getting the string from/.
[self formatMyNumber:dataString];
///..
-(void)formatMyNumber:(NSString *)numberString{
//resultLabel.text = numberString; //check to make sure string makes it to here.
//NSLog(#"hello From formatMyNumber method"); //check
}
//..
//the with send off each character to 4 animation methods that accept integers.
- (void)playAnimationToNumber:(int)number{
//...
//UpDated... weird stuff happening.
here is my method so far.
//Number Formatter
-(void)formatMyNumber:(NSString *)numberString{
NSLog(#"This is what is passed into the method%#",numberString);
int tempInt = (int)numberString;
NSLog(#"This is after I cast the string to an int %i",tempInt);
//[NSString alloc] stringWithFormat:#"%04d", numberString];
NSString *tempString = [[NSString alloc] initWithFormat:#"%04d", tempInt];
NSLog(#"This is after I try to put zeros infront %#",tempString);
//resultLabel.text = tempString;
//NSLog(#"hello From formatMyNumber method");
}
this is the output.
[Session started at 2011-06-19
16:18:45 +1200.] 2011-06-19
16:18:54.615 nissanCode0.1[4298:207]
731 2011-06-19 16:18:54.616
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] hello From
formatMyNumber method
As far as the number of zeros preceding your string goes there are a couple of ways to do this. I'd suggest:
NSString *myString = [NSString stringWithFormat:#"%04d",[dataString intValue]];
Is it possible you could have the number in integer form instead of string form? If so, it's pretty easy to use [NSString stringWithFormat:#"%04d", number]. See here for a list of the possible format specifiers.
See what stringWithFormat: can do. I realize you mentioned your numbers are NSStrings, but if they were ints, or you convert them back to ints, the following may do the trick. Modify the following to best suit your need:
return [NSString stringWithFormat:#"%04d", number];
I have an NSString with a number of sentences, and I'd like to split it into an NSArray of sentences. Has anybody solved this problem before? I found enumerateSubstringsInRange:options:usingBlock: which is able to do it, but it looks like it isn't available on the iPhone (Snow Leopard only). I thought about splitting the string based on periods, but that doesn't seem very robust.
So far my best option seems to be to use RegexKitLite to regex it into an array of sentences. Solutions?
Use CFStringTokenizer. You'll want to create the tokenizer with the kCFStringTokenizerUnitSentence option.
I would use a scanner for it,
NSScanner *sherLock = [NSCanner scannerWithString:yourString]; // autoreleased
NSMutableArray *theArray = [NSMutableArray array]; // autoreleased
while( ![sherLock isAtEnd] ){
NSString *sentence = #"";
// . + a space, your sentences probably will have that, and you
// could try scanning for a newline \n but iam not sure your sentences
// are seperated by it
[sherLock scanUpToString:#". " inToString:&sentence];
[theArray addObject:sentence];
}
This should do it, there could be some little mistakes in it but this is how I would do it.
You should lookup NSScanner in the docs though.. you might come across a method that is
better for this situation.
I haven't used them for a while but I think you can do this with NSString, NSCharacterSet and NSScanner. You create a character set that holds end sentence punctuation and then call -[NSScanner scanUpToCharactersFromSet:intoString:]. Each Scan will suck out a sentence into a string and you keep calling the method until the scanner runs out of string.
Of course, the text has to be well punctuated.
How about:
NSArray *sentences = [string componentsSeparatedByString:#". "];
This will return an array("One","Two","Three") from a string "One. Two. Three."
NSArray *sentences = [astring componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet] ];
I want my app to do something when the last NSLog has a certain string. I thought I could realize this with an if-query and isEqualtoString, but how can I make this?
Sorry for my bad English ;)
Maybe I don't understand what you're trying to do, but you can just create the string somewhere, log it, and then test it:
NSInteger _someInt = 2;
NSString *_someString = #"bananas";
NSString *_stringToBeLogged = [NSString stringWithFormat:#"%d %#", _someInt, _someString];
NSLog(#"%#", _stringToBeLogged);
if ([_stringToBeLogged isEqualToString:#"2 bananas"]) {
NSLog(#"I logged two bananas...");
}
You could consider creating your own custom log function which calls NSLog() after checking for your string constant. This would keep your code a bit cleaner if you want this functionality in multiple places and also allows you to easily extend the logging function further if desired.
i'm new to iphone programming and i encountered/noticed some problems while i was coding. which was after i typed a statement like
if (label.text > label2.text) {
do something...}
however, after typing my application can be compiled and run however when i try to validate it by comparing the values, my specified actions can run and i can change my image view image, however the conditions is not true but the specified actions can be run. Do enlighten me thanks! i will post my codes at the bottom, do comment if you spot any better practices? thanks once again.
Oh and how can i specify to check in my label that the default value is not "Label" or empty because i would like the values to be populated with number before commencing.
-(IBAction) beginMatch {
if (resultP1.text, resultP2.text = #"Label") {
errorMsg.text = #"Please Press Roll (:";
}
else
if (resultP1.text > resultP2.text) {
MG = [MainGameController alloc];
MG.player1 = playerName.text;
}
else {
MG.player1 = playerNameP2.text;
}
[self.view addSubview:MG.view];
}
this is one example that it does not work i have another one which is below.
-(IBAction) btn:(id) sender {
ptc = [playerTurnController alloc];
if (ptc.player1name = MGplayerName.text) {
if (lblDiceResultP1.text > lblDiceResultP2.text) {
img.image = [UIImage imageNamed:#"yellow.png"];
}
else if (ptc.player2name = MGplayerName.text) {
img.image = [UIImage imageNamed:#"Blue.png"];
}
}
}
Thank you.
Your code contains quite a few errors. You're trying to compare NSString values with ">", you're using the comma operator and = operator incorrectly, and you're allocating new objects in (what look to be) the wrong places.
You really should work your way through the introductory documentation on Apple's developer website first:
Learning Objective-C: A Primer
and
Your First iPhone Application
In here you're comparing string (alphabetically) addresses:
lblDiceResultP1.text > lblDiceResultP2.text
You probably want to extract NSNumbers of out the strings and compare the numeric values.
This here is an assignment and not a comparison:
ptc.player2name = MGplayerName.text
You probably meant to use == which is also wrong.
NSStrings are compared with the isEqualToString e.g.
NSString * s1 = #"String One";
NSString * s2 = #"String Two";
if([s1 isEqualToString:s2])
// do something when strings are equal
Trying to display a hebrew string that starts with a number, always displays the number at the end of the string like so: 1. יום שישי בבוקר
but I need the number to be displayed at the right side of the text-
any solution to that?
It happens with UILabel & UITextField & UITextView
and trying to write the number at the left side also produce the same resault.
Playing with combinations of UITextAlignment will doesn't help.
You don't need to change any setting on UILabel, just put the character with unicode 0x200F before your string. This is the reason:
In Unicode many characters have a specific directionality, which lets the system know it has to be written, say LTR, like سلام. The paragraph usually uses the direction of its first character. That's why your string without the number is typed from right to left automatically.
Now some characters, like numbers, have "weak" directionality, so they basically take that of their surrounding. When you type "1. בבוקר", the system first sees 1, so takes the usual LTR direction. Changing the alignment won't help, as it just shifts the whole text to right, or center.
To solve this issue, Unicode has two marker characters (LTR: 0x200E, RTL:200F). These are invisible, but dictate the directionality. So while "1. בבוקר" is...
בבוקר
if you type "#x200F" + "1. בבוקר" it will display like this:
1. בבוקר
Building on Mo's great answer:
This is the code Obj-C:
NSString *RTFstr = "1. בבוקר"; //This could be any right-to-left string
NSString *directionalString = [#"\u200F" stringByAppendingString:[note text]];
[someUITextView setString:directionalString];
And it actually works...
I had a slightly different problem but Mo's answer gave me the clue.
I wanted to get a LTR text (like "abcd") displayed in RTL direction ("dcba") without having to do myself the string reversing. Turns out enclosing the string between \u202E and \u202C does the trick.
I also recommend reading the following page as it gives a very good explanation of all these unicode magic:
http://www.iamcal.com/understanding-bidirectional-text/
Swift anybody?
extension String {
func stringByForcingWritingDirectionLTR() -> String {
return "\u{200E}".stringByAppendingString(self)
}
func stringByForcingWritingDirectionRTL() -> String {
return "\u{200F}".stringByAppendingString(self)
}
}
not sure if there's fancier way to do this but you might want to try something like this:
NSString *test = #"12. just a teststring";
NSString *number = [test substringToIndex: [test rangeOfString: #" "].location];
NSString *text = [test substringFromIndex: [test rangeOfString: #" "].location];
test = [NSString stringWithFormat: #"%# %#", text, number];
// test == "just a teststring 12."