how to remove particular words from strings? - iphone

I have an NSString *str, having value #"I like Programming and gaming."
I have to remove "I" "like" & "and" from my string so it should look like as "Programming gaming"
How can I do this, any Idea?

NSString *newString = #"I like Programming and gaming.";
NSString *newString1 = [newString stringByReplacingOccurrencesOfString:#"I" withString:#""];
NSString *newString12 = [newString1 stringByReplacingOccurrencesOfString:#"like" withString:#""];
NSString *final = [newString12 stringByReplacingOccurrencesOfString:#"and" withString:#""];
Assigned to wrong string variable edited now it is fine
NSLog(#"%#",final);
output : Programming gaming

NSString * newString = [#"I like Programming and gaming." stringByReplacingOccurrencesOfString:#"I" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"like" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"and" withString:#""];
NSLog(#"%#", newString);

More efficient and maintainable than doing a bunch of stringByReplacing... calls in series:
NSSet* badWords = [NSSet setWithObjects:#"I", #"like", #"and", nil];
NSString* str = #"I like Programming and gaming.";
NSString* result = nil;
NSArray* parts = [str componentsSeparatedByString:#" "];
for (NSString* part in parts) {
if (! [badWords containsObject: part]) {
if (! result) {
//initialize result
result = part;
}
else {
//append to the result
result = [NSString stringWithFormat:#"%# %#", result, part];
}
}
}

It is an old question, but I'd like to show my solution:
NSArray* badWords = #[#"the", #"in", #"and", #"&",#"by"];
NSMutableString* mString = [NSMutableString stringWithString:str];
for (NSString* string in badWords) {
mString = [[mString stringByReplacingOccurrencesOfString:string withString:#""] mutableCopy];
}
return [NSString stringWithString:mString];

Make a mutable copy of your string (or initialize it as NSMutableString) and then use replaceOccurrencesOfString:withString:options:range: to replace a given string with #"" (empty string).

Related

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

Substring after substring in NSString

I am new in objective and I'm facing my first problem, and I can not continue my first project.
it's quite simple, I have a NSString :
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
what I want to do is to get the value of the size "25" which is always 2 char long, so I can calculate my UILabel size.
i know how to detect if there is the substring I am looking for "size=" using :
if ([string rangeOfString:#"bla"].location == NSNotFound)
but I have not found or not understand how to extract the string #"size=XX" and then get the XX as a NSString from *myString
Thank for any help.
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSRange range = [myString rangeOfString:#"size="];
if (range.location != NSNotFound)
{
NSLog(#"Found \"size=\" at %d", range.location);
NSString *sizeString = [myString substringWithRange:NSMakeRange(range.location+5, 2)];
NSLog(#"sizeString: %#", sizeString);
}
This should do the trick. You could also at the end do this: int sizeFont = [sizeString intValue];
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
if ([myString rangeOfString:#"size"].location != NSNotFound)
{
myString = [myString substringFromIndex:[myString rangeOfString:#"size"].location];
myString = [myString substringToIndex:[myString rangeOfString:#" "].location]; // Now , myString ---> size=25 color='#d79198'> Here is some text !</font>
myString = [myString substringFromIndex:[myString length]-2];// Now, myString ---> size=25
NSLog(#"myString -- %#",myString); // Now, myString ---> 25
}
If you have string like stack:overflow then use it as follow :
NSString *Base=#"stack:overflow"
NSString *one = [[Base componentsSeparatedByString:#":"] objectAtIndex:0];
NSString *two = [[Base componentsSeparatedByString:#":"] objectAtIndex:1];
In this case one = stack and two=overflow
Part of an HTML page? Then use the tool that is designed for the task.
You could calculate the range of the number yourself or use a very simple regular expression to get the substring, something like
(?<=size\=)\d*
This means that you are searching for digits (\d*) that is preceded by "size=" ((?<=size\=))
Which using NSRegularExpression would be
NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"(?<=size\\=)\\d*"
options:0
error:&error];
NSTextCheckingResult *match =
[regex firstMatchInString:myString
options:0
range:NSMakeRange(0, [myString length])];
NSString *sizeText = [myString substringWithRange:match.range];
Finally you should convert the text "25" into a number using
NSInteger size = [sizeText integerValue];
Use componentsSeparatedByString: method...
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSString *theSizeString = [[[[myString componentsSeparatedByString:#" "] objectAtIndex:2] componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"The sizestring:%#",theSizeString);
I think it will be helpful to you.
You can get the range of the string #"size=". The range has location and length. So what you need next is to call on the myString the substringWithRange: method. The parameter would be an NSRage starting from the location+length of #"size=" and length of 2.

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

NSString select part go a string objective-c

I have problem with string. The string shows: ~00000000:termometr2: +26.9 st.C and I want to use only this part: +26.9 st.C in my textfield.text.
Thanks
NSString *fullStr = #"00000000:termometr2: +26.9 st.C";
NSArray *parts = [fullStr componentsSeparatedByString:#" "];
textField.text =[NSString stringWithFormat:#"%#",[parts objectAtIndex:1]];
it might help you:
NSArray *_array = [yourString componentsSeparatedByString:#":"];
[myTextField setText:[_array lastObject]]; // or any other component you want
Just do it this way, using the method stringByReplacingOccurrencesOfString: withString::
NSString *originalString = #"~00000000:termometr2: +26.9 st.C";
NSString *filteredString = [originalString stringByReplacingOccurrencesOfString:#"~00000000:termometr2: " withString:#""];

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];