Remove brackets from NSMutableString - ios

I have a NSMutableString like this:
(
993,
12836,
10630
)
how can i remove brackets?
EDIT
the string is the result of this instruction:
NSMutableString * result = [labelpost description];

You shouldn't rely on the description method as the format of the output it gives you is not guaranteed.
Instead, use a specific method on the object, like for an NSArray instance, use componentsJoinedByString: to create your desired string output.

string = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"()"]]

If it's NSString you can remove it by call:
string = [string stringByReplacingOccurancesOfString:#"(" withString:#""];
string = [string stringByReplacingOccurancesOfString:#")" withString:#""];

It looks to me like labelpost is an array. The method description generates a string that describes the contents of the object. In the case of an array, you get an open paren, then a comma-separated list of objects, then a closing bracket.
As the other poster, Greg, said, you can use stringByReplacingOccurancesOfString to convert your parens to empty strings, but then you will be left with
993,
12836,
10630
(With a blank line at the top containing a single space, newlines after every line, commas, and a space after the last object, and a final blank line.)
If that's what you want, fine. What is your final goal?
Try logging the class of labelpost and its contents:
NSLog(#"label post class = %#", [labelpost class]);
if ( [labelpost isKindOfClass:[NSArray class]] )
{
NSArray *array = (NSArray *)labelpost; //Cast labelpost to an array
for (id anObject in array)
NSlog(#"Object class = %#, object = %#", [anObject class] [anObject description]);
}

Related

How can I change substring(s) in an array of strings in Objective-C?

I have a weird error with decoding & sign so its always shown as &, so && will be &&, a&b is shown as a&b etc.
I have those weird characters in my array of strings sometimes, so I want to remove them. To be more clear, if I have an array like this:
"str1", "a&b", "12345", "d&&emo&"
I want to it to be:
"str1", "a&b", "12345", "d&&emo&"
So all & should be changed into just &.
This is the code I tried, but it didn't help. Elements are not changing their values:
for (int i = 0; i <= self.array-1; i++)
{
NSLog(#"%#", self.array[i]);
[self.array[i] stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSLog(#"%#", self.array[i]);
}
I am new to Objective-C.
NSString instances are immutable, which means you can't change them once they are created. The stringByReplacingOccurencesOfString:withString: method actually returns a new NSString instance. You could use NSMutableString, or alternatively, you can create a new array containing the replacement strings, e.g.:
NSMutableArray *newArray = [NSMutableArray array];
for (NSString *input in self.array)
{
NSString *replacement = [input stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
[newArray addObject:replacement];
}
self.array = newArray;

Unknown quotation marks added to string object in NSMutableArray after for loop

I have an array of NSString objects, the objects have some unneccessary chars (one object looks like this in the console: "\"stringContent\"") that I'm removing with the below code. It works correctly, however when I log arr1 50-60% of the strings got a quotation marks like this "stringContent", the others don't have it. Actually my problem is that I don't have an why it happens, because when I log the strings in the for loop they don't have the quotation marks. Do anybody has an idea what can causes this?
NSMutableArray * arr1 = [[NSMutableArray alloc ]init];
for (NSString *str in self.stringArray) {
NSString *newString = [str substringToIndex:[brand length]-1];
NSString *nwstr = [newString substringFromIndex:1];
[arr1 addObject:nwstr];
NSLog(#"string %#", nwstr);
}
NSLog(#"array %#", arr1);
Other thing that might be helpful, when I call this every object appears in the console, it's like the quotation marks are hidden for the containsString method, because a lot of them don't meet the requirement of the if statement.
for (NSString *str in arr1) {
if (![str containsString:#"\""]) {
NSLog(#"XXX %#", str);
}
}
When you NSLog an NSArray or NSDictionary, the elements are displayed in a log format which MAY (or may not) include gratuitous quotation marks, escaped characters, etc. Specifically, quotation marks are used around strings, EXCEPT when the strings contain no non-alphabetic characters or blanks.
More detail: What actually happens is that NSLog internally invokes [NSString stringWithFormat:] or one of its kin to format the text to be logged. stringWithFormat:, in turn, invokes the description method of each object in the parameter list that corresponds to a %# format directive. It is the description method of NSArray and NSDictionary which adds the extra characters.

stringWithFormat returning newline

I am adding objects to a mutable array by selecting choice(s) from my table view and viewing them in a text field. When I use stringWithFormat, the line of code is automatically adding in characters.
Example: I choose Bob from my table view
Bob
When I do a NSLog, it is actually appearing as
(
Bob
)
But what is appearing in the text field is
( Bob)
Because there is
(\n Bob\n)
Here is the code that I am using to rid of the parentheses and replace commas with semicolons.
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
// NSString
combinedForces = [ourForces stringByReplacingOccurrencesOfString:#"," withString:#";"];
// NSString
twoCombindForces = [combinedForces stringByReplacingOccurrencesOfString:#"(" withString:#""];
// NSString
UltmateCombinedForces = [twoCombindForces stringByReplacingOccurrencesOfString:#")" withString:#""];
//personnel is the text field
personnel.text = UltmateCombinedForces;
Question now is : What is a less messy path to get
( Bob)
to appear as
Bob
in my text field?
Solution update: After the following lines:
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
Include the following line of code:
personnel.text = [AllNames componentsJoinedByString:#";"];
That got rid of the (\n Bob\n) extra characters that were showing up in the field. Thank you all for you help and wisdom. =)
Use componentsJoinedByString: after filling the AllNames array:
personnel.text = [AllNames componentsJoinedByString:#";"];
OK, I think I understand what you're trying to do now.
You have an array of names...
NSArray *names = #[#"Bob", #"Sam", #"Dave"];
And you want a string of all these names...
#"Bob; Sam; Dave"
You seem to be separating them with a semi colon though? ; Is that correct?
You can do this with...
NSString *nameList = [names componentsJoinedByString:#"; "];
But I'm not entirely sure that this is what you're trying to achieve.
In NSLog the output expression
(
Bob
)
represents an array. To get rid of the parentheses and newlines instead of
NSLog(#"%#", AllNames[0]);
write
NSLog(#"%#", AllNames[0][0]);
… and please use variable names starting with a lowercase letter.
You can use NSCharacter Set to remove items you don't want.. The below might offer a less messy solution.
NSString *originalText = #"( Bob) ";
NSMutableCharacterSet *unwantedChars = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[unwantedChars addCharactersInString:#"()"];
NSString *refinedText = [[originalText componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString:#""];

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

How to filter a string after a particular character in iOS? [duplicate]

This question already has answers here:
Split an NSString to access one particular piece
(7 answers)
Closed 9 years ago.
I want to filter string after character '='. For eg if 8+9=17 My output should be 17. I can filter character before '=' using NSScanner, how to do its reverse??? I need a efficient way to do this without using componentsSeparatedByString or creating an array
Everyone seems to like to use componentsSeparatedByString but it is quite inefficient when you just want one part of a string.
Try this:
NSString *str = #"8+9=17";
NSRange equalRange = [str rangeOfString:#"=" options:NSBackwardsSearch];
if (equalRange.location != NSNotFound) {
NSString *result = [str substringFromIndex:equalRange.location + equalRange.length];
NSLog(#"The result = %#", result);
} else {
NSLog(#"There is no = in the string");
}
Update:
Note - for this specific example, the difference in efficiencies is negligible if it is only being done once.
But in general, using componentsSeparatedByString: is going to scan the entire string looking for every occurrence of the delimiter. It then creates an array with all of the substrings. This is great when you need most of those substrings.
When you only need one part of a larger string, this is very wasteful. There is no need to scan the entire string. There is no need to create an array. There is no need to get all of the other substrings.
NSArray * array = [string componentsSeparatedByString:#"="];
if (array)
{
NSString * desiredString = (NSString *)[array lastObject]; //or whichever the index
}
else
{
NSLog(#""); //report error - = not found. Of array could somehow be not created.
}
NOTE:
Though this is very popular splitting solution, it is only worth trying whenever every substring separated by separator string is required. rmaddy's answer suggest better mechanism whenever the need is only to get small part of the string. Use that instead of this approach whenever only small part of the string is required.
Try to use this one
NSArray *arr = [string componentsSeparatedByString:#"="];
if (arr.count > 0)
{
NSString * firstString = [arr objectAtIndex:0];
NSString * secondString = [arr objectAtIndex:1];
NSLog(#"First String %#",firstString);
NSLog(#"Second String %#",secondString);
}
Output
First String 8+9
Second String 17
Use this:
NSString *a =#"4+6=10";
NSLog(#"%#",[a componentsSeparatedByString:#"="])
;
Log: Practice[7582:11303] (
"4+6",
10
)

Resources