How can I get a substring between predefined strings. For example:
NSString* sentence = #"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = #"{start}";
NSString* end = #"{end}";
NSString* myWord = [do some stuff with:sentence and:start and:end];
NSLog(#"myWord - %#",myWord);
Log: myWord - this
The following will give you the output you want:
NSString* sentence = #"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = #"{start}";
NSString* end = #"{end}";
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];
if (startRange.location != NSNotFound && endRange.location != NSNotFound) {
NSString *myWord = [sentence substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length)];
NSLog(#"myWord - %#", myWord);
}
else {
NSLog(#"myWord not found");
}
You can use rangeOfString:to get the location of each of the markers. Then use subStringWithRange:to extract the string part you want.
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence end];
NSString myWord = [NSString subStringWithRange:NSMakeRange(startRange.location+startRange.length, endRange.location-startRange.location+startRange.length)];
All code typed in Safari and no error handling included!
NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];
int startLocation = startRange.location + startRange.length;
int lenght = endRange.location - startLocation;
NSString* myWord = [sentence substringWithRange:NSMakeRange(startLocation, lenght)];
Related
This question already has answers here:
Swift: Remove specific characters of a string only at the beginning
(6 answers)
Closed 5 years ago.
My string text is Like -
1) .....bla ..bla...
2)...bla.. bla…bla.
3).bla.. bla…bla.
dots are not static.I want to remove dots only from starting. not All dots
I have tried with this
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"." withString:#""];
but this is removing all dots.
try this.
NSString* regex = #"^\\.*";
NSString* input = #"....abc..z";
NSString* output = [input stringByReplacingOccurrencesOfString:regex withString:#"" options:NSRegularExpressionSearch range: [input rangeOfString:input]];
var test = "...abc";
while test.hasPrefix(".") {
test.remove(at: test.startIndex)
}
//test variable will have dots removed at the start.
Try this.
Try this:
NSString *str = #"...Videt...IDL";
__block NSInteger loc = 0;
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
loc = substringRange.location;
*stop = YES;
}];
NSString *convStr = [str substringFromIndex:loc];
NSLog(#"%#", convStr);
NSString *str = #"....bla .... bla..... bla";
NSCharacterSet *charSet = [NSCharacterSet letterCharacterSet];
int letterNO = 0;
for (int i =0; i<str.length; i++)
{
NSString *letter = [NSString stringWithFormat:#"%c",[str characterAtIndex:i]];
if ([letter rangeOfCharacterFromSet:charSet].location != NSNotFound)
{
letterNO = i;
break;
}
}
NSString * newString = [str substringFromIndex:letterNO];
NSLog(#"newString %#",newString);
How to find word in NSString and check characters before and after this word?
"This pattern has two parts separated by the"
How to find tern and how to check the character before and after
Before word character:"t"
After word character:" "
You can use NSScanner to get indexes of these two characters.
Example:
NSString *string = #"tern";
NSScanner *scanner = [[NSScanner alloc] initWithString:#"This pattern has two parts separated by the"];
[scanner scanUpToString:string intoString:nil];
NSUInteger indexOfChar1 = scanner.scanLocation - 1;
NSUInteger indexOfChar2 = scanner.scanLocation + string.length;
You can also use a rangeOfString method:
Example:
NSRange range = [sourceString rangeOfString:stringToLookFor];
NSUInteger indexOfChar1 = range.location - 1;
NSUInteger indexOfChar2 = range.location +range.length + 1;
Then, when you have indexes, getting the characters is easy:
NSString *firstCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar1, 1)];
NSString *secondCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar2, 1)];
Hope this helps.
Here is an implementation using Regular Expressions
NSString *testString= #"This pattern has two parts separated by the";
NSString *regexString = #"(.)(tern)(.)";
NSRegularExpression* exp = [NSRegularExpression
regularExpressionWithPattern:regexString
options:NSRegularExpressionSearch error:&error];
if (error) {
NSLog(#"%#", error);
} else {
NSTextCheckingResult* result = [exp firstMatchInString:testString options:0 range:NSMakeRange(0, [testString length] ) ];
if (result) {
NSRange groupOne = [result rangeAtIndex:1]; // 0 is the WHOLE string.
NSRange groupTwo = [result rangeAtIndex:2];
NSRange groupThree = [result rangeAtIndex:3];
NSLog(#"[%#][%#][%#]",
[testString substringWithRange:groupOne],
[testString substringWithRange:groupTwo],
[testString substringWithRange:groupThree] );
}
}
Results:
[t][tern][ ]
Its better to get pre and post character in NSString to avoid handling of unicode characters.
NSString * testString = #"This pattern has two parts separated by the";
NSString * preString;
NSString * postString;
NSUInteger maxRange;
NSRange range = [testString rangeOfString:#"tern"];
if(range.location == NSNotFound){
NSLog(#"Not found");
return;
}
if (range.location==0) {
preString=nil;
}
else{
preString = [testString substringWithRange:NSMakeRange(range.location-1,1)];
}
maxRange = NSMaxRange(range);
if ( maxRange >=testString.length ) {
postString = nil;
}
else{
postString = [testString substringWithRange:NSMakeRange(range.location+range.length, 1)];
}
I have a string like this
<img alt=\"Marco Bueno\" src=\"http://u.goal.com/136600/136687_thumb.jpg\" style=\"float: left;margin:0 10px 10px 10px;\" title=\"Marco Bueno\" /><p style=\"float:left;\">Herrera is currently on national team duty representing the U-23 side that has already made history at the Toulon Tournament, while Bueno won the U-17 World Cup in 2011</p>
I want to get the "src"(http://u.goal.com/136600/136687_thumb.jpg) from this string. How can i get that in a dynamic way.
Thanks!!
You can get your url using like this...
NSRange divRange = [dateString rangeOfString:#"src=\"" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [dateString length] - endDivRange.location;
endDivRange = [dateString rangeOfString:#".jpg" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location + endDivRange.length;
NSLog(#"BinarySecurityToken : %#",[dateString substringWithRange:divRange]);
}
}
Output :
http://u.goal.com/136600/136687_thumb.jpg
you can get the String between two String like
-(NSString*)stringBetweenString:(NSString*)start andString:(NSString)end {
NSRange startRange = [self rangeOfString:start];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [self length] - targetRange.location;
NSRange endRange = [self rangeOfString:end options:0 range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
return [self substringWithRange:targetRange];
}
}
return nil;
}
Use this :
NSString *aString = #"<img alt=\"Marco Bueno\" src=\"http://u.goal.com/136600/136687_thumb.jpg\" style=\"float: left;margin:0 10px 10px 10px;\" title=\"Marco Bueno\" /><p style=\"float:left;\">Herrera is currently on national team duty representing the U-23 side that has already made history at the Toulon Tournament, while Bueno won the U-17 World Cup in 2011</p>";
NSRange r1 =[aString rangeOfString:#"src=\""];
NSRange r2 =[aString rangeOfString:#"\" style"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *subString = [aString substringWithRange:rSub];
Hope it helps you.
In my program I'm getting an html notification tag use
"<script>p(34,'1','hello world');</script>/r/n"
I need now is to get the string "hello world" from above tag and it should be a dynamic process as the length of text varies for every response tag.
Something like this will work. You may have to adjust the fromString and toString if those parts of the message are also dynamic, but this will get you started.
NSString *someString = #"<script>p(34,'1','hello world');</script>/r/n";
NSString *fromString = #"<script>p(34,'1','";
NSRange fromRange = [someString rangeOfString:fromString];
NSString *toString = #"');</script>/r/n";
NSRange toRange = [someString rangeOfString:toString];
NSRange range = NSMakeRange(fromRange.location + fromRange.length, toRange.location - (fromRange.location + fromRange.length));
NSString *result = [someString substringWithRange:range];
Please try to use this one.... I Hope this work will fine..
NSString *data = #"<script>p(34,'1','hello world');</script>/r/n";
NSRange divRange = [data rangeOfString:#"','" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [data length] - endDivRange.location;
endDivRange = [data rangeOfString:#"'" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
NSLog(#"SubString %#",[data substringWithRange:divRange]);
}
}
NSString * myString = #"<script>p(34,'1','hello world');</script>/r/n";//#" hello(1234)";
NSRange range1 = [myString rangeOfString:#"," options:NSBackwardsSearch];
NSRange range2 = [myString rangeOfString:#"'" options:NSBackwardsSearch];
if ((range1.length == 1) && (range2.length == 1) && (range2.location > range1.location))
{
NSRange range3;
range3.location = range1.location+2;
range3.length = (range2.location - range1.location)-2;
NSString *subString = [myString substringWithRange:range3];
NSLog(#"%#",subString)
}
outPut----> hello world
I have a string as this.
NSString *myString = #"{53} balloons";
How do I get the substring 53 ?
NSString *myString = #"{53} balloons";
NSRange start = [myString rangeOfString:#"{"];
NSRange end = [myString rangeOfString:#"}"];
if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
NSString *betweenBraces = [myString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
}
edit: Added range check, thx to Keab42 - good point.
Here is what I did.
NSString *myString = #"{53} balloons";
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
NSArray *splitString = [myString componentsSeparatedByCharactersInSet:delimiters];
NSString *substring = [splitString objectAtIndex:1];
the substring is 53.
For Swift 4.2:
if let r1 = string.range(of: "{")?.upperBound,
let r2 = string.range(of: "}")?.lowerBound {
print (String(string[r1..<r2]))
}
You can use a regular expression to get the number between the braces. It might seem a bit complicated but the plus side is that it will find multiple numbers and the position of the number doesn't matter.
Swift 4.2:
let searchText = "{53} balloons {12} clowns {123} sparklers"
let regex = try NSRegularExpression(pattern: "\\{(\\d+)\\}", options: [])
let matches = regex.matches(in: searchText, options: [], range: NSRange(searchText.startIndex..., in: searchText))
matches.compactMap { Range($0.range(at: 1), in: searchText) }
.forEach { print("Number: \(searchText[$0])") }
Objective-C:
NSString *searchText = #"{53} balloons {12} clowns {123} sparklers";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:searchText
options:0
range:NSMakeRange(0, searchText.length)];
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSLog(#"Number: %#", [searchText substringWithRange:numberRange]);
}
This will print out:
Number: 53
Number: 12
Number: 123
Try this code.
NSString *myString = #"{53} balloons";
NSString *value = [myString substringWithRange:NSMakeRange(1,2)];
For Swift 2.1 :-
var start = strData?.rangeOfString("{")
var end = strData?.rangeOfString("}")
if (start!.location != NSNotFound && end!.location != NSNotFound && end!.location > start!.location) {
var betweenBraces = strData?.substringWithRange(NSMakeRange(start!.location + 1, end!.location-(start!.location + 1)))
print(betweenBraces)
}
I guess, your a looking for the NSScanner class, at least if you are addressing a general case. Have a look in Apples documentation.
Search the location for "{" and "}".
Take substring between those index.
Checked with any number of data:
NSString *str = #"{53} balloons";
NSArray* strary = [str componentsSeparatedByString: #"}"];
NSString* str1 = [strary objectAtIndex: 0];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSLog(#"number = %#",str2);
Another method is
NSString *tmpStr = #"{53} balloons";
NSRange r1 = [tmpStr rangeOfString:#"{"];
NSRange r2 = [tmpStr rangeOfString:#"}"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *subString = [tmpStr substringWithRange:rSub];
If you don't know how many digits there will be, but you know it will always be enclosed with curly braces try this:
NSString *myString = #"{53} balloons";
NSRange startRange = [myString rangeOfString:#"{"];
NSRange endRange = [myString rangeOfString:#"}"];
if (startRange.location != NSNotFound && endRange.location != NSNotFound && endRange.location > startRange.location) {
NSString *value = [myString substringWithRange:NSMakeRange(startRange.location,endRange.ocation - startRange.location)];
}
There's probably a more efficient way to do it though.