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

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

Related

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

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

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

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) }