Objective C - OSX NSInterger to NSString - objective-c

Hi i am reading a book by aaron hillegass on cococa programming and I doing one of the mini tasks he asks us to do.
the task is to create an application that has one window open and has 1 input text field, a button and a label.
when a user inputs some text and presses the button, the label displays the text and the length of the text inputted.
Here is what I have got so far
//retrieve text from textfield
NSString *string = [textFieldInput stringValue];
//retrieve length of text and store in NSInteger called length
NSInteger length = [string length];
//store length in string format
NSString *string_length = [NSString stringWithFormat:#"%d", length];
//join strings
NSString *full_string = [string stringByAppendingString:(#"has ",string_length,#" characters")];
//set label text
[textField setStringValue:full_string];
however the actual string is shown and the characters string is shown, just not the string_length. any suggestions and am i going about this in the right way? Thanks.

NSString *fullString = [string stringByAppendingFormat:#"has %# characters", string_length];

//retrieve text from textfield
NSString *string = [textFieldInput stringValue];
NSString *fullString = [string stringByAppendingFormat:#" has %d characters", [string length]];
//set label text
[textField setStringValue:fullString];

Your usage of stringByAppendingString: is wrong.
If I understand you correctly, you are trying to pass a list of strings that should be appended to string but that method only takes a single string argument.
You can try the following:
NSString* fullString = [string stringByAppendingString:[NSString stringWithFormat:#"%# %# %#", #"has ", string_length, #" characters"]];

Related

Get a substring from an NSString until arriving to any letter in an NSArray - objective C

I am trying to parse a set of words that contain -- first greek letters, then english letters. This would be easy if there was a delimiter between the sets.That is what I've built so far..
- (void)loadWordFileToArray:(NSBundle *)bundle {
NSLog(#"loadWordFileToArray");
if (bundle != nil) {
NSString *path = [bundle pathForResource:#"alfa" ofType:#"txt"];
//pull the content from the file into memory
NSData* data = [NSData dataWithContentsOfFile:path];
//convert the bytes from the file into a string
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
//split the string around newline characters to create an array
NSString* delimiter = #"\n";
incomingWords = [string componentsSeparatedByString:delimiter];
NSLog(#"incomingWords count: %lu", (unsigned long)incomingWords.count);
}
}
-(void)parseWordArray{
NSLog(#"parseWordArray");
NSString *seperator = #" = ";
int i = 0;
for (i=0; i < incomingWords.count; i++) {
NSString *incomingString = [incomingWords objectAtIndex:i];
NSScanner *scanner = [NSScanner localizedScannerWithString: incomingString];
NSString *firstString;
NSString *secondString;
NSInteger scanPosition;
[scanner scanUpToString:seperator intoString:&firstString];
scanPosition = [scanner scanLocation];
secondString = [[scanner string] substringFromIndex:scanPosition+[seperator length]];
// NSLog(#"greek: %#", firstString);
// NSLog(#"english: %#", secondString);
[outgoingWords insertObject:[NSMutableArray arrayWithObjects:#"greek", firstString, #"english",secondString,#"category", #"", nil] atIndex:0];
[englishWords insertObject:[NSMutableArray arrayWithObjects:secondString,nil] atIndex:0];
}
}
But I cannot count on there being delimiters.
I have looked at this question. I want something similar. This would be: grab the characters in the string until an english letter is found. Then take the first group to one new string, and all the characters after to a second new string.
I only have to run this a few times, so optimization is not my highest priority.. Any help would be appreciated..
EDIT:
I've changed my code as shown below to make use of NSLinguisticTagger. This works, but is this the best way? Note that the interpretation for english characters is -- for some reason "und"...
The incoming string is: άγαλμα, το statue, only the last 6 characters are in english.
int j = 0;
for (j=0; j<incomingString.length; j++) {
NSString *language = [tagger tagAtIndex:j scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqual: #"und"]) {
NSLog(#"j is: %i", j);
int k = 0;
for (k=0; k<j; k++) {
NSRange range = NSMakeRange (0, k);
NSString *tempString = [incomingString substringWithRange:range ];
NSLog (#"tempString: %#", tempString);
}
return;
}
NSLog (#"Language: %#", language);
}
Alright so what you could do is use NSLinguisticTagger to find out the language of the word (or letter) and if the language has changed then you know where to split the string. You can use NSLinguisticTagger like this:
NSArray *tagschemes = #[NSLinguisticTagSchemeLanguage];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options: NSLinguisticTagPunctuation | NSLinguisticTaggerOmitWhitespace];
[tagger setString:#"This is my string in English."];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
//Loop through each index of the string's characters and check the language as above.
//If it has changed then you can assume the language has changed.
Alternatively you can use NSSpellChecker's requestCheckingOfString to get teh dominant language in a range of characters:
NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
[spellChecker setAutomaticallyIdentifiesLanguages:YES];
NSString *spellCheckText = #"Guten Herr Mustermann. Dies ist ein deutscher Text. Bitte löschen Sie diesen nicht.";
[spellChecker requestCheckingOfString:spellCheckText
range:(NSRange){0, [spellCheckText length]}
types:NSTextCheckingTypeOrthography
options:nil
inSpellDocumentWithTag:0
completionHandler:^(NSInteger sequenceNumber, NSArray *results, NSOrthography *orthography, NSInteger wordCount) {
NSLog(#"dominant language = %#", orthography.dominantLanguage);
}];
This answer has information on how to detect the language of an NSString.
Allow me to introduce two good friends of mine.
NSCharacterSet and NSRegularExpression.
Along with them, normalization. (In Unicode terms)
First, you should normalize strings before analyzing them against a character set.
You will need to look at the choices, but normalizing to all composed forms is the way I would go.
This means an accented character is one instead of two or more.
It simplifies the number of things to compare.
Next, you can easily build your own NSCharacterSet objects from strings (loaded from files even) to use to test set membership.
Lastly, regular expressions can achieve the same thing with Unicode Property Names as classes or categories of characters. Regular expressions could be more terse but more expressive.

Space or tab then it should not be considered as a character

I am having text view in my app. I need to validate input of a text view. The rules are as below
Tab/Space cannot be accepted in the begining of the text entry
Tab/Space can be accepted in the middle and end of the text entry
Max characters accepted can be 256
How do I develop this, first character filteration logic ?
I have written following code in my app but it's still not giving me proper output ...Can anybody tell me where is the mistake???
-(void)textViewDidBeginEditing:(UITextView *)textView
{
NSString *rawString = [textView text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0)
{
// Text was empty or only whitespace.
}
NSLog(#"length = %d",[trimmed length]);
[self.scrollView adjustOffsetToIdealIfNeeded];
}
Try this
NSString *string = [txtview text];;
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"%d",trimmedString.length);

Chinese string in the text of a label

I have a label where I have to put a string in Chinese extracted from a database, but nothing comes out. I noticed that the string is not pulled from database, while all other work correctly. What can I do?
char *subTitle= (char*)sqlite3_column_text(statement,13);
NSLog(#" The sutitle is %s", subTitle);
//The sutitle is
rowTable.sottotitolo = [[NSString alloc]initWithUTF8String: subTitle];
NSLog(#"The subtitle is %#", rowTable.sottotitolo);
//The subtitle is
Using methods other than Western alphabet?
NSLog(#"The string in chinese is %#", self.chinaTable.subtitle);
//The string in chinese is
//is not printed to the screen,but the database is written correctly
self.labelTitle.text = self.chinaTable.subtitle;
//empty out
Thanks in advance
While you retrieving your data from sqlite, instead of specifying the encoding schema, use this:
NSString *myChineseText = [NSString stringWithFormat:#"%s",(const char*)sqlite3_column_text(statement, index)];
NSLog(#"%#",myChineseText);
Hope, it'll solved your problem. :)
Try CFStringConvertEncodingToNSStringEncoding and kCFStringEncodingBig5_E.
Also see apple doc and for international
or for creating own encoding see
and this
unichar ellipsis = 0x2026;
NSString *theString = [NSString stringWithFormat:#"To be continued%C", ellipsis];
// custom encoding
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSChineseTrad);
NSData *asciiData = [theString dataUsingEncoding:encoding
allowLossyConversion:YES];
NSString *asciiString = [[NSString alloc] initWithData:asciiData
encoding:encoding];

Making a backspace button for a calculator

I am making an iOS calculator and it I'm having minor difficulties with the backspace button (for deleting the last number of the value displayed on a label).
To get the current value on the label I use
double currentValue = [screenLabel.text doubleValue]
Following other questions, I tried something like
-(IBAction)backspacePressed:(id)sender
{
NSMutableString *string = (NSMutableString*)[screenLabel.text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1]
;
[screenLabel.text setText:[NSString stringWithFormat:#"%#",temp]];
}
But it does not work,
(Xcode says "setText is deprecated", "NSString may not respond to setText" and that an identifier is expected in the first line of code inside the IBAction)
and I do not really understand this code to make it work by myself.
What should I do?
It should be
[screenLabel setText:[NSString stringWithFormat:#"%#",temp]];
Your Xcode clearly says that you are trying to call setText' method on anNSStringwhere as you should be calling that on aUILabel. YourscreenLabel.textis retuning anNSString. You should just usescreenLabelalone and should callsetText` on that.
Just use,
NSString *string = [screenLabel text];
The issue with that was that, you are using [screenLabel.text]; which is not correct as per objective-c syntax to call text method on screenLabel. Either you should use,
NSString *string = [screenLabel text];
or
NSString *string = screenLabel.text;
In this method, I dont think you need to use NSMutableString. You can just use NSString instead.
In short your method can be written as,
-(IBAction)backspacePressed:(id)sender
{
NSString *string = [screenLabel text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
[screenLabel setText:temp];
}
As per your question in comments(which is deleted now), if you want to display zero when there are no strings present, try,
-(IBAction)backspacePressed:(id)sender
{
NSString *string = [screenLabel text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
if ([temp length] == 0) {
temp = #"0";
}
[screenLabel setText:temp];
}

string formatting in a cocoa tutorial

I am doing a Cocoa tutorial where I need to count the characters in a field, then output something like 'the_string_i_am_count' has 21 characters.
I have managed to get the string, count it, and output the count but I have no idea how to output the count along with the string and the other info.
How would I do this?
-(IBAction)countCharacters:(id)sender
{
//i had to connect this to the class also to make it get the value.
//NSString *string = [inputField stringValue];
//get the number of chars
NSUInteger length = [[inputField stringValue] length];
[outputField setIntValue:length]; //string];
//[outputField setStringValue: #"'s' has %d characters.", string, length];
}
Semi working code:
-(IBAction)countCharacters:(id)sender
{
//i had to connect this to the class also to make it get the value.
NSString *string = [inputField stringValue];
//get the number of chars
NSUInteger length = [[inputField stringValue] length];
[outputField setStringValue:[NSString stringWithFormat:#"'%s' has %d characters.", string, length]];
}
[outputField setStringValue:[NSString stringWithFormat:#"%# has %# characters.", string, length]];