Array in UITextView - iphone

I have a text view in which I want to display NSArray *result as text of the text view.
For eg:
result={#"home",#"Office",#"Park",#"Market",nil};
textView text should be:
home
office
park
market

for(int i =0 ; i <[Array Count] ;i++)
{
self.textView.text = [NSString stringWithFormat:#"%# %#",self.textView.text, Array objectAtIndex:i];
}
Correct any spelling mistake.

You can use componentsJoinedByString: method, like this:
NSString *text = [result componentsJoinedByString:#" "];
You can use a different separator instead of #" ".

You can use a for loop as such:
NSString *str =#"";
for (NSString *tmp in result) {
str = [NSString stringWithFormat:#"%# %#",str,tmp];
}
If you want each entry on a new line replace the space with "\n".

Related

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

How to create a comma-separated string?

I want to create a comma-separated string like this.
NSString *list = #"iPhone,iPad,iPod";
I tried like this,
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
But the issue is I'm getting a string like this
#"iPhone,iPad,iPod," Note that there is an extra comma "," at the end of the string. How can I avoid that extra comma?
Can you please give me a hint. Highly appreciated
Thanks in advance
To join an array of strings into a single string by a separator (character which would be a string), you could use this method of NSArray class:
NSArray* array = #[#"iPhone", #"iPad", #"iPod"];
NSString* query = [array componentsJoinedByString:#","];
By using this method, you won't need to drop the last extra comma (or whatever) because it won't add it to the final string.
There's a couple of routes you can take.
If the number of items is always the same, and known before hand (which I guess isn't the case, but I mention it for completeness's sake), just make the whole string at once:
[NSString stringWithFormat:#"%#,%#,%#", [[arrItems objectAtIndex:0] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:1] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:2] objectForKey:#"ItemList"]]
Knowing that the unwanted comma will always be the last character in the string, you can make removing it the last step in construction:
} // End of loop
[strItemList removeCharactersInRange:(NSRange){[strItemList length] - 1, 1}];
Or you can change your thinking a little and do the loop like this:
NSString * comma = #"";
for( i = 0; i < [arrItems count]; i++ ){
[strItemList appendString:[NSString stringWithFormat:#"%#%#", comma, [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
comma = #",";
}
Notice that comma comes before the other item. Setting that string inside the loop means that nothing will be added on the first item, but a comma character will be for every other item.
After Completion of loop add below stmt
strItemList = [strItemList substringToIndex:[strItemList length]-1]
check the value of array count if array count is last then add without comma else add with comma. try this out i am not sure to much about.
if([arrItems objectAtIndex:i] == arrItems.count){
[strItemList appendString:[NSString stringWithFormat:#"%#", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
else {
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
Assuming that arrItems is an NSArray with elements #"iPhone", #"iPad", and #"iPod", you can do this:
NSArray *list = [arrItems componentsJoinedByString:#","]
NSArray with elements #"iPhone", #"iPad", and #"iPod"
NSString *str=[[arrItems objectAtIndex:0]objectForKey:#"ItemList"]]
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:1]objectForKey:#"ItemList"]]];
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:2]objectForKey:#"ItemList"]]];
NsLog(#"%#",str);
// Assuming...
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPhone", #"iPodTouch", nil] forKey:#"ItemList"];
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPad", #"iPad2", #"Apple TV", nil] forKey:#"ItemList"];
NSDictionary *dictionary3 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iMac", #"MacBook Pro", #"Mac Pro", nil] forKey:#"ItemList"];
NSArray *arrItems = [NSArray arrayWithObjects:dictionary1, dictionary2, dictionary3, nil];
// create string list
NSString *strItemList = [[arrItems valueForKeyPath:#"#unionOfArrays.ItemList"] componentsJoinedByString:#", "];
NSLog(#"All Items List: %#", strItemList);
Output:
All Items List: iPhone, iPodTouch, iPad, iPad2, Apple TV, iMac, MacBook Pro, Mac Pro
This method will return you the nsmutablestring with comma separated values from an array
-(NSMutableString *)strMutableFromArray:(NSMutableArray *)arr withSeperater:(NSString *)saperator
{
NSMutableString *strResult = [NSMutableString string];
for (int j=0; j<[arr count]; j++)
{
NSString *strBar = [arr objectAtIndex:j];
[strResult appendString:[NSString stringWithFormat:#"%#",strBar]];
if (j != [arr count]-1)
{
[strResult appendString:[NSString stringWithFormat:#"%#",seperator]];
}
}
return strResult;
}

iphone remove next string - leave rest of string after particular occurrence of string

In objective c how to Remove text after a string occurrence.
for example i have to remove a text after occurrence of text 'good'
'iphone is good but..' here i have to remove the but text in the end so the text will be now 'iphone is good'
Try with below code
NSString *str_good = #"iphone is good but...";
NSRange range = [str_good rangeOfString:#"good"];
str_good = [str_good substringToIndex:range.location+range.length];
NSString * a = #"iphone is good but..";
NSRange match = [a rangeOfString:#"good"];
NSString * b = [a substringToIndex:match.location+match.length];
If you want to remove rest of the string after a particular occurrence of "but", you can get the range of "but" and trim the original string down
NSString * test = [NSString stringWithString:#"iphone is good but rest of string"];
NSRange range = [test rangeOfString:#"but"];
if (range.length > 0) {
NSString *adjusted = [test substringToIndex:range.location];
NSLog(#"result %#", adjusted);
}
EDIT
We can assume that the search does not want to cut of "butter is yellow", and can change the range to include " but"
NSRange range = [test rangeOfString:#" but"];
Try this:-
NSArray *array = [string componentsSeperatedBy:#"good"];
NSString *requiredString = [array objectAtIndex:0];
NSArray *array = [string componentsSeparatedByString:stringToSearch];
NSString *requiredString;
if ([array count] > 0) {
requiredString = [[array objectAtIndex:0] stringByAppendingString:stringToSearch];
}

Split one string into different strings

i have the text in a string as shown below
011597464952,01521545545,454545474,454545444|Hello this is were the message is.
Basically i would like each of the numbers in different strings to the message eg
NSString *Number1 = 011597464952
NSString *Number2 = 01521545545
etc
etc
NSString *Message = Hello this is were the message is.
i would like to have that split out from one string that contains it all
I would use -[NSString componentsSeparatedByString]:
NSString *str = #"011597464952,01521545545,454545474,454545444|Hello this is were the message is.";
NSArray *firstSplit = [str componentsSeparatedByString:#"|"];
NSAssert(firstSplit.count == 2, #"Oops! Parsed string had more than one |, no message or no numbers.");
NSString *msg = [firstSplit lastObject];
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:#","];
// print out the numbers (as strings)
for(NSString *currentNumberString in numbers) {
NSLog(#"Number: %#", currentNumberString);
}
Look at NSString componentsSeparatedByString or one of the similar APIs.
If this is a known fixed set of results, you can then take the resulting array and use it something like:
NSString *number1 = [array objectAtIndex:0];
NSString *number2 = [array objectAtIndex:1];
...
If it is variable, look at the NSArray APIs and the objectEnumerator option.
NSMutableArray *strings = [[#"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#",|"]] mutableCopy];
NString *message = [[strings lastObject] copy];
[strings removeLastObject];
// strings now contains just the number strings
// do what you need to do strings and message
....
[strings release];
[message release];
does objective-c have strtok()?
The strtok function splits a string into substrings based on a set of delimiters.
Each subsequent call gives the next substring.
substr = strtok(original, ",|");
while (substr!=NULL)
{
output[i++]=substr;
substr=strtok(NULL, ",|")
}
Here's a handy function I use:
///Return an ARRAY containing the exploded chunk of strings
///#author: khayrattee
///#uri: http://7php.com
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}

getting the same value in each cell of table view in objective-c

i have check by printing the value of the cell.textlable.text in each iteration of the loop each time the value of it is as i want, but as the time of output on the simulator the value is come same for each row of cell.
my code:
for(i=0;i<[appDelegate.books count];i++)
{
Book *aBook= [appDelegate.books
objectAtIndex:i];
NSString *string1 =aBook.Latitude;
NSString *trimmedString = [string1
stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]];
double myDouble = [trimmedString doubleValue];
NSString *string2=aBook.Longitude;
NSString *trimmedString1 = [string2
stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]];
double mDouble = [trimmedString1 doubleValue];
if((((myDouble<(a+5.021777))&&(myDouble>(a-
8)))||((mDouble<=(b+10))&&(mDouble>=(b-10)))))
{
NSString *a1=aBook.AreaName;
NSString *b1=[a1 stringByAppendingString:#","];
NSString *s=aBook.STREET_NAME;
NSString *c=[b1 stringByAppendingString:s];
cell.textLabel.text = c ;
}
}
return cell; }
The problem is likely this line:
for(i=0;i<[appDelegate.books count];i++)
That's going to loop through every item in appDelegate.books. Assuming that that's an NSArray and that this code is inside your -tableView:cellForRowAtIndexPath: method, replace that line and the next with the following:
Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];
(This, of course, assumes that the row numbers match the index numbers in the array. If not, adjust to match.)