Extracting from the right of a string in objective C [duplicate] - ios

This question already has answers here:
Get last 2 characters of a string?
(2 answers)
Closed 9 years ago.
This seems to be what I'm looking for but in reverse. I would like the string to extract from the right not from the left.
The example extracting from the left is given:
NSString *source = #"0123456789";
NSString *firstFour = [source substringToIndex:4];
Output: "0123"
I'm looking for a version of the below that works from the right (what is below doesn't work)
NSString *source = #"0123456789";
NSString *lastFour = [source substringToIndex:-4];
Output: "6789"
the [source substringFromIndex:6]; won't work because sometimes I will get an answer that is 000123456789 or 456789 or 6789. In all cases I just need the last 4 characters from the string so that I can convert it to a number.
there must be a better way than a bunch of if else statements?

As you are not sure, about the length of the string, so you must check it before extracting like this:
NSString *source = #"0123456789";
NSNumber *number;
if (source.length>=4) {
NSString *lastFour=[source substringFromIndex:source.length-4];
number=#([lastFour integerValue]); //and save it in a number, it can be int or NSInteger as per your need
}
NSLog(#"%#",number);
Also if you want a quick method that you need to call several times, create a category :
#implementation NSString (SubstringFromRight)
-(NSString *)substringFromRight:(NSUInteger)from{
if (self.length<from) {
return nil;
}
return [self substringFromIndex:self.length-from];
}
#end
And use it as :NSLog(#"%#",[source1 substringFromRight:4]);

NSString *source = #"0123456789";
NSString *newString = [source substringFromIndex:[source length] - 4];
NSLog(#"%#",newString);

replace
NSString *lastFour = [source substringToIndex:-4];
with
NSString *lastFour = [source substringFromIndex:[source length] - 4];
which returns you the last 4 characters of your original string string in lastFour string.

You can use the following code to get last 4 characters from your string.
NSString *last4Characters = [source substringFromIndex:(source.length - 4)];
NSLog(#"Last 4 Characters:%#",last4Characters);
last4Characters=nil;
Please let me know if any issue.

Related

Display Unicode String as Emoji

I currently receive emojis in a payload in the following format:
\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F
which represents "🚣‍♀️"
However, if I try to display this, it only shows the string above (escaped with 1 less ), not the emoji e.g.
NSString *emoji = payload[#"emoji"];
NSLog(#"%#", emoji) then displays as \U0001F6A3\U0000200D\U00002640\U0000FE0F
It's as if the unicode escape it not being recognised. How can I get the string above to show as an emoji?
Please assume that the format the data is received in from the server cannot be changed.
UPDATE
I found another way to do it, but I think the answer by Albert posted below is better. I am only posting this for completeness and reference:
NSArray *emojiArray = [unicodeString componentsSeparatedByString:#"\\U"];
NSString *transformedString = #"";
for (NSInteger i = 0; i < [emojiArray count]; i++) {
NSString *code = emojiArray[i];
if ([code length] == 0) continue;
NSScanner *hexScan = [NSScanner scannerWithString:code];
unsigned int hexNum;
[hexScan scanHexInt:&hexNum];
UTF32Char inputChar = hexNum;
NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
transformedString = [transformedString stringByAppendingString:res];
}
Remove the excess backslash then convert with a reverse string transform stringByApplyingTransform. The transform must use key "Any-Hex" for emojis.
NSString *payloadString = #"\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F";
NSString *unescapedPayloadString = [payloadString stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NSString *transformedString = [unescapedPayloadString stringByApplyingTransform:#"Any-Hex" reverse:YES];
NSLog(#"%#", transformedString);//logs "🚣‍♀️"
I investigated this, and it seems you may not be receiving what you say you are receiving. If you see \U0001F6A3\U0000200D\U00002640\U0000FE0F in your NSLog, chances are you are actually receiving \\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F at your end instead. I tried using a variable
NSString *toDecode = #"\U0001F6A3\U0000200D\U00002640\U0000FE0F";
self.tv.text = toDecode;
And in textview it is displaying the emoji fine.
So you got to fix that first and then it will display well.

In objective-c how to get characters after n-th?

I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];

Replace String Between Two Strings

I have a serious problem about indexing in array. I've been working on this for 2 days and couldn't find answer yet.
I want to do that, search specific character in array then replace it with other string. I'm using replaceObjectAtIndex method but my code is doesn't work.
Here is my code;
NSString *commentText = commentTextView.text;
NSUInteger textLength = [commentText length];
NSString *atSign = #"#";
NSMutableArray *commentArray = [[NSMutableArray alloc] init];
[commentArray addObject:commentText];
for (int arrayCounter=1; arrayCounter<=textLength; arrayCounter++)
{
NSRange isRange = [commentText rangeOfString:atSign options:NSCaseInsensitiveSearch];
if(isRange.location != NSNotFound)
{
commentText = [commentText stringByReplacingOccurrencesOfString:commentText withString:atSign];
[_mentionsearch filtrele:_mentionText];
id<textSearchProtocol> delegate;
[delegate closeList:[[self.searchResult valueForKey:#"user_name"] objectAtIndex:indexPath.row]];
}
}
Ok, now i can find "#" sign in the text and i can match it. But this is the source of problem that, i can not replace any string with "#" sign. Here is the last part of code;
-(void)closeList
{
NSArray *arrayWithSign = [commentTextView.text componentsSeparatedByString:#" "];
NSMutableArray *arrayCopy = [arrayWithSign mutableCopy];
[arrayCopy replaceObjectAtIndex:isRange.location withObject:[NSString stringWithFormat:#"#%#",username]];
}
When im logging isRange.location value, it returns correct. But when im try to run, my application is crashing. So, i can not replacing [NSString stringWithFormat:#"#%#",username] parameter. How can i solve this problem?
If I understand correctly you want to change a substring in a string with a new string. In this case, why don't you use directly the stringByReplacingOccurrencesOfString method of NSString:
NSString *stringToBeChanged = #"...";
NSString *stringToBeChangedWith = #"...";
NSString *commentTextNew = [commentText stringByReplacingOccurrencesOfString:stringToBeChanged withString:stringToBeChangedWith];

ios - NSString URL decode? [duplicate]

This question already has answers here:
urldecode in objective-c
(6 answers)
Closed 9 years ago.
I'm trying to Decode URL,but i'm getting warning message like "NSString may not respond to URLDecode".
NSString* token = [[urlStr substringFromIndex:r.location + 1] URLDecode];
Any ideas?
Because it is not a method a classic NSString respond to, you can though add a category like the following, to add the method yourself :
#interface NSString (URLDecode)
- (NSString *)URLDecode;
#end
#implementation NSString
- (NSString *)URLDecode
{
NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
#end
Try like this.
NSString* urlEncoded = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and check this link https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/TP40003744
it may help you.

Split NSString and Limit the response

I have a string Hello-World-Test, I want to split this string by the first dash only.
String 1:Hello
String 2:World-Test
What is the best way to do this? What I am doing right now is use componentsSeparatedByString, get the first object in the array and set it as String 1 then perform substring using the length of String 1 as the start index.
Thanks!
I added a category on NSString to split on the first occurrence of a given string. It may not be ideal to return the results in an array, but otherwise it seems fine. It just uses the NSString method rangeOfString:, which takes an NSString(B) and returns an NSRange showing where that string(B) is located.
#interface NSString (Split)
- (NSArray *)stringsBySplittingOnString:(NSString *)splitString;
#end
#implementation NSString (Split)
- (NSArray *)stringsBySplittingOnString:(NSString *)splitString
{
NSRange range = [self rangeOfString:splitString];
if (range.location == NSNotFound) {
return nil;
} else {
NSLog(#"%li",range.location);
NSLog(#"%li",range.length);
NSString *string1 = [self substringToIndex:range.location];
NSString *string2 = [self substringFromIndex:range.location+range.length];
NSLog(#"String1 = %#",string1);
NSLog(#"String2 = %#",string2);
return #[string1, string2];
}
}
#end
Use rangeOfString to find if split string exits and then use substringWithRange to create new string on bases of NSRange.
For Example :
NSString *strMain = #"Hello-World-Test";
NSRange match = [strMain rangeOfString:#"-"];
if(match.location != NSNotFound)
{
NSString *str1 = [strMain substringWithRange: NSMakeRange (0, match.location)];
NSLog(#"%#",str1);
NSString *str2 = [strMain substringWithRange: NSMakeRange (match.location+match.length,(strMain.length-match.location)-match.length)];
NSLog(#"%#",str2);
}

Resources