how to remove () charracter - iphone

when i convert my array by following method , it adds () charracter.
i want to remove the () how can i do it..
NSMutableArray *rowsToBeDeleted = [[NSMutableArray alloc] init];
NSString *postString =
[NSString stringWithFormat:#"%#",
rowsToBeDeleted];
int index = 0;
for (NSNumber *rowSelected in selectedArray)
{
if ([rowSelected boolValue])
{
profileName = [appDelegate.archivedItemsList objectAtIndex:index];
NSString *res = [NSString stringWithFormat:#"%d",profileName.userID];
[rowsToBeDeleted addObject:res];
}
index++;
}
UPDATE - 1
when i print my array it shows like this
(
70,
71,
72
)

Here's a brief example of deleting the given characters from a string.
NSString *someString = #"(whatever)";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSMutableString *mutableCopy = [NSMutableString stringWithString:someString];
NSRange range;
for (range = [mutableCopy rangeOfCharacterFromSet:charSet];
range.location != NSNotFound;
[mutableCopy deleteCharactersInRange:range],
range = [mutableCopy rangeOfCharacterFromSet:charSet]);
All this does is get a mutable copy of the string, set up a character set with any and all characters to be stripped from the string, and find and remove each instance of those characters from the mutable copy. This might not be the cleanest way to do it (I don't know what the cleanest is) - obviously, you have the option of doing it Ziminji's way as well. Also, I abused a for loop for the hell of it. Anyway, that deletes some characters from a string and is pretty simple.

Try using NSArray’s componentsJoinedByString method to convert your array to a string:
[rowsToBeDeleted componentsJoinedByString:#", "];

The reason you are getting the parenthesis is because you are calling the toString method on the NSArray class. Therefore, it sounds like you just want to substring the resulting string. To do this, you can use a function like the following:
+ (NSString *) extractString: (NSString *)string prefix: (NSString *)prefix suffix: (NSString *)suffix {
int strLength = [string length];
int begIndex = [prefix length];
int endIndex = strLength - (begIndex + [suffix length]);
if (endIndex > 0) {
string = [string substringWithRange: NSMakeRange(begIndex, endIndex)];
}
return string;
}

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 do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

IOS : NSString retrieving a substring from a string

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.
For example
http://bla.com/bla?id=%1234%&something=%888%
What I want to extract is from id=% to the next %.
Any idea's?
Use the rangeOfString method:
NSRange range = [string rangeOfString:#"id=%"];
if (range.location != NSNotFound)
{
//range.location is start of substring
//range.length is length of substring
}
You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:
NSString *param = nil;
NSRange start = [string rangeOfString:#"id=%"];
if (start.location != NSNotFound)
{
param = [string substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:#"%"];
if (end.location != NSNotFound)
{
param = [param substringToIndex:end.location];
}
}
//param now contains your value (or nil if not found)
Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
if ([parts count] > 1)
{
NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
result[key] = value;
}
}
return result;
}
This doesn't strip the % characters from the values, but you can do that either with
NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];
Or with something like
NSString *value = [value stringByReplacingOccurencesOfString:#"%" withString:#""];
UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).
Try this
NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* day = [foo objectAtIndex: 0];

NSString to NSArray

I want to split an NSString into an NSArray. For example, given:
NSString *myString=#"ABCDEF";
I want an NSArray like:
NSArray *myArray={A,B,C,D,E,F};
How to do this with Objective-C and Cocoa?
NSMutableArray *letterArray = [NSMutableArray array];
NSString *letters = #"ABCDEF𝍱क्";
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length])
options:(NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[letterArray addObject:substring];
}];
for (NSString *i in letterArray){
NSLog(#"%#",i);
}
results in
A
B
C
D
E
F
𝍱
क्
enumerateSubstringsInRange:options:usingBlock: available for iOS 4+ can enumerate a string with different styles. One is called NSStringEnumerationByComposedCharacterSequences, what will enumerate letter by letter but is sensitive to surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters, all referred as Composed Character
Note, that the accepted answer "swallows" 𝍱and breaks क् into क and ्.
Conversion
NSString * string = #"A B C D E F";
NSArray * array = [string componentsSeparatedByString:#" "];
//Notice that in this case I separated the objects by a space because that's the way they are separated in the string
Logging
NSLog(#"%#", array);
This is what the console returned
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]];
for (int i=0; i < [theString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%C", [theString characterAtIndex:i]];
[chars addObject:ichar];
}
This link contains examples to split a string into a array based on sub strings and also based on strings in a character set. I hope that post may help you.
here is the code snip
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Without loop you can use this:
NSString *myString = #"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];
if([myString length] != 0)
{
NSError *error = NULL;
// declare regular expression object
NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:#"(.)" options:NSMatchingReportCompletion error:&error];
// replace each match with matches character + <space> e.g. 'A' with 'A '
[regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:#"$0 "];
// trim last <space> character
[tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:#""];
// split into array
NSArray * arr = [tempStr componentsSeparatedByString:#" "];
// print
NSLog(#"%#",arr);
}
This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString with <space> to return an array
Swift 4.2:
String to Array
let list = "Karin, Carrie, David"
let listItems = list.components(separatedBy: ", ")
Output : ["Karin", "Carrie", "David"]
Array to String
let list = ["Karin", "Carrie", "David"]
let listStr = list.joined(separator: ", ")
Output : "Karin, Carrie, David"
In Swift, this becomes very simple.
Swift 3:
myString.characters.map { String($0) }
Swift 4:
myString.map { String($0) }

Replace multiple characters in a string in Objective-C?

In PHP I can do this:
$new = str_replace(array('/', ':', '.'), '', $new);
...to replace all instances of the characters / : . with a blank string (to remove them)
Can I do this easily in Objective-C? Or do I have to roll my own?
Currently I am doing multiple calls to stringByReplacingOccurrencesOfString:
strNew = [strNew stringByReplacingOccurrencesOfString:#"/" withString:#""];
strNew = [strNew stringByReplacingOccurrencesOfString:#":" withString:#""];
strNew = [strNew stringByReplacingOccurrencesOfString:#"." withString:#""];
Thanks,
matt
A somewhat inefficient way of doing this:
NSString *s = #"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", s); // => foobarbazfoo
Look at NSScanner and -[NSString rangeOfCharacterFromSet: ...] if you want to do this a bit more efficiently.
There are situations where your method is good enough I think matt.. BTW, I think it's better to use
[strNew setString: [strNew stringByReplacingOccurrencesOfString:#":" withString:#""]];
rather than
strNew = [strNew stringByReplacingOccurrencesOfString:#"/" withString:#""];
as I think you're overwriting an NSMutableString pointer with an NSString which might cause a memory leak.
Had to do this recently and wanted to share an efficient method:
(assuming someText is a NSString or text attribute)
NSString* someText = #"1232342jfahadfskdasfkjvas12!";
(this example will strip numbers from a string)
[someText stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [someText length])];
Keep in mind that you will need to escape regex literal characters using Obj-c escape character:
(obj-c uses a double backslash to escape special regex literals)
...stringByReplacingOccurrencesOfString:#"[\\\!\\.:\\/]"
What makes this interesting is that NSRegularExpressionSearch option is little used but can lead to some very powerful controls:
You can find a nice iOS regex tutorial here and more on regular expressions at regex101.com
Essentially the same thing as Nicholas posted above, but if you want to remove everything EXCEPT a set of characters (say you want to remove everything that isn't in the set "ABCabc123") then you can do the following:
NSString *s = #"A567B$%C^.123456abcdefg";
NSCharacterSet *doNotWant = [[NSCharacterSet characterSetWithCharactersInString:#"ABCabc123"] invertedSet];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", s); // => ABC123abc
Useful in stripping out symbols and such, if you only want alphanumeric.
+ (NSString*) decodeHtmlUnicodeCharactersToString:(NSString*)str
{
NSMutableString* string = [[NSMutableString alloc] initWithString:str]; // #&39; replace with '
NSString* unicodeStr = nil;
NSString* replaceStr = nil;
int counter = -1;
for(int i = 0; i < [string length]; ++i)
{
unichar char1 = [string characterAtIndex:i];
for (int k = i + 1; k < [string length] - 1; ++k)
{
unichar char2 = [string characterAtIndex:k];
if (char1 == '&' && char2 == '#' )
{
++counter;
unicodeStr = [string substringWithRange:NSMakeRange(i + 2 , 2)]; // read integer value i.e, 39
replaceStr = [string substringWithRange:NSMakeRange (i, 5)]; // #&39;
[string replaceCharactersInRange: [string rangeOfString:replaceStr] withString:[NSString stringWithFormat:#"%c",[unicodeStr intValue]]];
break;
}
}
}
[string autorelease];
if (counter > 1)
return [self decodeHtmlUnicodeCharactersToString:string];
else
return string;
}
Here is an example in Swift 3 using the regularExpression option of replacingOccurances.
Use replacingOccurrences along with a the String.CompareOptions.regularExpression option.
Example (Swift 3):
var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)
Output:
7Hello, 7play7ground777
If the characters you wish to remove were to be adjacent to each other you could use the
stringByReplacingCharactersInRange:(NSRange) withString:(NSString *)
Other than that, I think just using the same function several times isn't that bad. It is much more readable than creating a big method to do the same in a more generic way.
Create an extension on String...
extension String {
func replacingOccurrences(of strings:[String], with replacement:String) -> String {
var newString = self
for string in strings {
newString = newString.replacingOccurrences(of: string, with: replacement)
}
return newString
}
}
Call it like this:
aString = aString.replacingOccurrences(of:['/', ':', '.'], with:"")