i want a program to display the reverse of a string. my program should have two textViews and a button. the string entered by user in a textView should be taken when we press the button and the reverse of that string should be displayed in the other textView. all the ib stuff to be done on window itself.
plz help me with code.
forgive me if you feel the question is simple or basic.
I would suggest you read in the values from the textview into an array then reverse the array, something like this where array1 is a list of values from your textview
NSMutableArray *tmp = [[NSMutableArray alloc] init];
for(int x=[array1 count] - 1;x>=0; x--){
[tmp addObject:[array1 objectAtIndex:x]];
}
What about this?
-(NSString *) revertString:(NSString*)stringToRevert
{
NSMutableString *reversedStr;
int len = [stringToRevert length];
reversedStr = [NSMutableString stringWithCapacity:len];
while (len > 0)
[reversedStr appendString:
[NSString stringWithFormat:#"%C", [stringToRevert characterAtIndex:--len]]];
return reversedStr;
}
Related
I'm displaying an array of contacts ( [[ContactStore sharedStore]allContacts] ) in a tableview and have divided the list into alphabetic sections. I have used the following code to return an array of the first letters of the contacts, and a dictionary of the number of entries per letter.
//create an array of the first letters of the names in the sharedStore
nameIndex = [[NSMutableArray alloc] init];
//create a dictionary to save the number of names for each first letter
nameIndexCount = [[NSMutableDictionary alloc]init];
for (int i=0; i<[[[ContactStore sharedStore]allContacts]count]; i++){
//Get the first letter and the name of each person
Contact *p = [[[ContactStore sharedStore]allContacts]objectAtIndex:i];
NSString *lastName = [p lastName];
NSString *alphabet = [lastName substringToIndex:1];
//If that letter is absent from the dictionary then add it and set its value as 1
if ([nameIndexCount objectForKey:alphabet] == nil) {
[nameIndex addObject:alphabet];
[nameIndexCount setValue:#"1" forKey:alphabet];
//If its already present add one to its value
} else {
NSString *newValue = [NSString stringWithFormat:#"%d", ([[nameIndexCount valueForKey:alphabet] intValue] + 1)];
[nameIndexCount setValue:newValue forKey:alphabet];
}
}
This works, however it is very slow when the array is large, I'm sure there's a better way to do this but I'm quite new to this so am not sure how. Are there any suggestions for a better way to do this?
Although Bio Cho has a good point, you might see an increase in performance by calling
[[ContactStore sharedStore]allContacts]
only once. For example:
nameIndex = [[NSMutableArray alloc] init];
nameIndexCount = [[NSMutableDictionary alloc] init];
/*
Create our own copy of the contacts only once and reuse it
*/
NSArray* allContacts = [[ContactStore sharedStore] allContacts];
for (int i=0; i<[allContacts count]; i++){
//Get the first letter and the name of each person
Contact *p = allContacts[i];
NSString *lastName = [p lastName];
NSString *alphabet = [lastName substringToIndex:1];
//If that letter is absent from the dictionary then add it and set its value as 1
if ([nameIndexCount objectForKey:alphabet] == nil) {
[nameIndex addObject:alphabet];
[nameIndexCount setValue:#"1" forKey:alphabet];
//If its already present add one to its value
} else {
NSString *newValue = [NSString stringWithFormat:#"%d", ([[nameIndexCount
valueForKey:alphabet] intValue] + 1)];
[nameIndexCount setValue:newValue forKey:alphabet];
}
}
Though I can't say for sure, I'd guess that repeatedly accessing your shared store is what's killing you. Maybe only accessing it once will give you what you need.
Consider storing your contacts in Core Data and using an NSFetchedResultsController.
The NSFetchedResultsController will only load a subset of the rows which are visible on the table view, thus preventing your user from having to wait for all the contacts to be sorted.
NSFetchedResultsController will also sort your contacts by an attribute (ie. first or last name), and you can set your section titles to be the first letter of the field you're sorting by.
Take a look at this question and this tutorial.
I'm reading a text file line by line, and storing it into a NSArray.
What I want to achieve is to increment the index of my NSArray when the user clicks a button.
Code:
text.editable = NO;
NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"firstyea" ofType:#"txt"] encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
NSArray *lines = [fileString componentsSeparatedByString:#"\n"]; // each line, adjust character for line endings
NSString *wat = [lines objectAtIndex:1];
text.text = wat;
[self.view addSubview:text];
So I have to increment objectAtIndex by 1 whenever the user clicks a button.
I can do it in C++ by having a variable of type int, and saying something like objectAtIndex:counter++ but I don't know how to do the same thing in IOS.
You can't do it with NSArray, you need to use a NSMutableArray
You should take a variable of type static int.
For example:
static int counter=0; //define it globally
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
[tempArray insertObject:#"Your Data From File" atIndex:counter++];
Note: Don't forget to release the array after you're finished using it!
Declare an integer i globally. #property int i;
in
viewDidLoad
, declare i=0;
-(IBAction)BtnClick:(id)sender
{
if ( i < lines.count )
{
NSString *wat = [lines objectAtIndex:i];
i=i+1;
}
}
Hope this helps.
What are alternatives for these controls in iPhone
Radio Button
Check Box
Drop Down
x raise to Power y in UILabel
Hyperlink
Suggestion and answers will be appreciated, thanks.
Radio Button: UISegmentedControl
Check Box: UISwitch
Drop Down: UIPickerView
x raise to Power y in UILabel: no such thing, you need to draw it
yourself.
Hyperlink: Use a UILabel and attach a gesture recognizer for taps to
it (or a custom type button)
Almost all of these controls can be displayed using a UIWebView - if that's not an option, have a look at the UIWebView implementations and it should give you some kind of idea.
However, if you want native controls, these are probably the best options:
Radio Button: UISegmnetedControl
Check Box: UISwitch
Drop Down: UIPickerView (used in UIWebView).
x to the power of y in a UILabel is easy. Just replace your indices with unicode superscript characters... I use the following method to turn an integer into a string with superscript characters.
+(NSString *)convertIntToSuperscript:(int)i {
NSArray *array = [[NSArray alloc] initWithObjects:#"⁰", #"¹", #"²", #"³", #"⁴", #"⁵", #"⁶", #"⁷", #"⁸", #"⁹", nil];
if (i >= 0 && i <= 9) {
NSString *myString = [NSString stringWithFormat:#"%#", [array objectAtIndex:i]];
[array release];
return myString;
}
else {
NSString *base = [NSString stringWithFormat:#"%i", i];
NSMutableString *newString = [[NSMutableString alloc] init];
for (int b = 0; b<[base length]; b++) {
int temp = [[base substringWithRange:NSMakeRange(b, 1)] intValue];
[newString appendString:[array objectAtIndex:temp]];
}
[array release];
NSString *returnString = [NSString stringWithString:newString];
[newString release];
return returnString;
}
}
For a hyperlink, use a UITextView with Property Inspector -> Detection -> Links enabled and Editable behavior disabled. Of course this is also available in a UIWebView.
I have a paragraph (4 sentences) of text in an .plist array that loads into a UITextView.
By default, it presents the text how it is, as one big lump of text in a paragraph. I want to know if it is possible to split this up?
Such as Line 1: sdfafasfsafsa, then line 2: asfdsafs, line 3: adfsfsdfsdfa, etc.
Is there a way I can search for a . and then separate the lines accordingly? I would just edit the plist manually but there are hundreds of entries so it isn't easy to do.
NSString* tidiedString = [sourceString stringByReplacingOccurrencesOfString:#"." withString:#"\n"];
Update: OK, so more detail is coming through. You could use a regular expression - but if you're not familiar, the learning curve is a bit steep. Otherwise, as with other answers, crank through the list. You need to take care of whitespaces, empty lines etc. The following snippet isn't pretty, but will do the job.
NSString* sourceString = #"Hyperlinks can be great. They can also dilute your focus and tempt you into putting off what you most want to do. Here I chose to place links at the foot of the page to help you to make an active choice as to whether to surf or refocus your attention elsewhere.";
NSArray* arrayOfStrings = [sourceString componentsSeparatedByString:#"."];
NSMutableString* superString = [NSMutableString stringWithString:#""];
int lineCount = 1;
for (NSString* string in arrayOfStrings)
{
if ([string length] < 1) continue;
[superString appendFormat:#"Line %d: %#.\n", lineCount++, [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
[superString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[[self userEntry] setText:superString];
NSArray *array = [sourceString componentsSeparatedByString:#"."];
NSMutableString *resultString= [[NSMutableString alloc] init];
int linecount=1;
for(NSString *lines in array)
{
[resultString appendString:[NSString stringWithFormat:#"Line%i:%#\n",linecount++,lines]];
}
NSLog(#"resultString:%#",resultString);
this may help..!!
Try making a loop that runs through the array and that adds every line to the UITextView plus #"\n".
So something like...:
NSString *curText = txtView.text;
NSString *lineBreak = #"\n";
txtView.text=[NSString stringWithFormat:#"%# + %#", curText, lineBreak];
Or just replace the dots by #"\n".
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I concatenate strings in Objective-C?
Firstly, the platform is iPhone and label.text changes the label displayed. Consider this scenario:
I've an array of integers. And I want to display it on the screen.
Here's my take on it:
-(IBAction) updateText: (id)sender {
int a[2];
a[0]=1;
a[1]=2;
a[2]=3;
for (int i=0; i<=10;i++)
label.text = [NSString stringByAppendingString: [NSString stringWithFormat: #"%i", a[i]]];
}
As you can probably see, I'm pretty confused. Pls pls help me out :(
Try this:
NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
[theString appendString:[NSString stringWithFormat:#"%i ",i]];
}
label.text = theString;
Since you're using a loop, do be somewhat careful with both Tom and Benjie's solutions. They each create an extra autoreleased object per iteration. For a small loop, that's fine, but if the size of the loop is unbounded or if the strings are large, this can lead to a very large memory spike and performance hit. Particularly on iPhone, this is exactly the kind of loop that can lead to surprising memory problems due to short-lived memory spikes.
The following solution has a smaller memory footprint (it's also slightly faster and takes less typing). Note the call to -appendFormat: rather than -appendString. This avoids creating a second string that will be thrown away. Remember that the final string has an extra space at the end that you may want to get rid of. You can fix that by either treating the first or last iteration differently, or by trimming the last space after the loop.
NSMutableString* theString = [NSMutableString string];
for (int i=0; i<=10;i++){
[theString appendFormat:#"%i ",i];
}
label.text = theString;
Don't forget [NSArray componentsJoinedByString:]. In this case you don't have an NSArray, but in the common cases where you do, this is probably the best way to get what you're looking for.
//NSArray *chunks
string = [chunks componentsJoinedByString: #","];
Another method without using NSMutableString:
NSString* theString = #"";
for (int i=0; i<=10;i++){
theString = [theString stringByAppendingFormat:#"%i ",i];
}
label.text = theString;
Here's a full implementation (correcting your ranges):
-(IBAction) updateText: (id)sender {
int a[3];
a[0]=1;
a[1]=2;
a[2]=3;
NSString *str = #"";
for (int i=0; i<3;i++)
str = [str stringByAppendingFormat:#"%i ",i];
label.text = str;
}
You could also do it like this (e.g. if you wanted a comma separated list):
-(IBAction) updateText: (id)sender {
int a[3];
a[0]=1;
a[1]=2;
a[2]=3;
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
for (int i=0; i<3;i++)
[arr addObject:[NSString stringWithFormat:#"%i",i]];
label.text = [arr componentsJoinedByString:#", "];
}