NSString with Emojis - objective-c

I have a NSArray containing NSStrings with emoji codes in the following format:
0x1F463
How can I now convert them into a NSString with the correct format?
With this method I am able to generate an "Emoji"-NSString:
NSString *emoji = [NSString stringWithFormat:#"\U0001F463"];
But this is only possible with constant NSStrings. How can I convert the whole NSArray?

Not my best work, but it appears to work:
for (NSString *string in array)
{
#autoreleasepool {
NSScanner *scanner = [NSScanner scannerWithString:string];
unsigned int val = 0;
(void) [scanner scanHexInt:&val];
NSString *newString = [[NSString alloc] initWithBytes:&val length:sizeof(val) encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", newString);
[newString release]; // don't use if you're using ARC
}
}
Using an array of four of your sample value, I get four pairs of bare feet.

You can do it like this:
NSString *str = #"0001F463";
// Convert the string representation to an integer
NSScanner *hexScan = [NSScanner scannerWithString:str];
unsigned int hexNum;
[hexScan scanHexInt:&hexNum];
// Make a 32-bit character from the int
UTF32Char inputChar = hexNum;
// Make a string from the character
NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
// Print the result
NSLog(#"%#", res);

Related

How to convert NSString intoNSArray?

I have an NSString which is a mathematical expression. I have operators (+,-,*,/) and operands (digits from 0 to 9,integers,decimals etc). I want to convert this NSString into NSArray. For example if my NSString is "7.9999-1.234*-9.21". I want NSArray having elements 7.9999,-,1.234,*,-,9.21 in the same order. How can I accomplish this?
I have tried a code. It dosent work in all scenarios though. Here It is:
code:
NSString *str=#"7.9999-1.234*-9.21";
NSMutableArray *marray=[[NSMutableArray alloc] init];
for(i=0;i<6;i++)
{
[marray addObject:[NSNull null]];
}
NSMutableArray *operands=[[NSMutableArray alloc] initWithObjects:#"7.9999",#"1.234",#"9.21",nil];
NSMutableArray *operators=[[NSMutableArray alloc] initWithObjects:#"-",#"*",#"-",nil];
for(i=0,j=0,k=0,l=0;i<=([str length]-1),j<[operands count],k<[operators count],l<[marray count];i++)
{
NSString *element=[[NSString alloc] initWithFormat:#"%c",[str characterAtIndex:i]];
BOOL res=[element isEqualToString:#"+"]||[element isEqualToString:#"-"]||[element isEqualToString:#"*"]||[element isEqualToString:#"/"];
if(res==0)
{
[marray replaceObjectAtIndex:l withObject:[operands objectAtIndex:j]];
}
else
{
l++;
[marray replaceObjectAtIndex:l withObject:[operators objectAtIndex:k]];
k++,l++,j++;
}
}
for(i=0;i<6;i++)
{
NSLog(#"%#",[marray objectAtIndex:i]);
}
Here str is the string to be converted. My array is the array obtained by converting the string str. When I execute this code I get the following on console:
7.9999
-
1.234
*
<null>
-
You should use NSScanner, scanning up to your operator characters, then when you find one, save the scanned string and then save the operator into the array and skip the operator (setScanLocation:). Continue doing this till you get to the end of the string (in a loop, one iteration for each operator).
NSArray * marray = [str componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"+-*/"]
];
ThankYou #Wain and #Hinata Hyuga.I figured out a code that would work to convert any string to array with the help of your suggestions.
Here is the code
NSMutableArray *convArray=[[NSMutableArray alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:inputString];
NSCharacterSet *opSet=[NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
[scanner setCharactersToBeSkipped:opSet];
int i;
for(i=0;i<[inputString length];)
{
if([inputString characterAtIndex:i]=='+'||[inputString characterAtIndex:i]=='-'||[inputString characterAtIndex:i]=='*'||[inputString characterAtIndex:i]=='/')
{
[convArray addObject:[[NSString alloc] initWithFormat:#"%c",[inputString characterAtIndex:i]]];
i++;
}
else
{
NSString *oprnd;
[scanner scanUpToCharactersFromSet:opSet intoString:&oprnd];
[convArray addObject:oprnd];
i=i+[inputString rangeOfString:oprnd].length;
}
}
return convArray;

How to parse a string format like [***]***?

I need to parse a string like [abc]000, and what I want to get is an array containing abc and 000. Is there an easy way to do it?
I'm using code like this:
NSString *sampleString = #"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:#"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:#"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
But it's inefficient and didn't check whether the string is in a format like [**]**.
For this simple pattern, can just parse yourself like:
NSString *s = #"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
NSUInteger i = [s rangeOfString:#"]"].location;
if (i != NSNotFound) {
firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
lastPart = [s substringFromIndex:i + 1];
}
}
Or you could learn to use the NSScanner class.
As always, there are lots of ways to do this.
OPTION 1
If these are fixed length strings (each part is always three characters) then you can simply get the substrings directly:
NSString *sampleString = #"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
OPTION 1 (shortened)
NSArray *parts = #[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(#"%#", parts);
OPTION 2
If they aren't always three characters, then you can use NSScanner:
NSString *sampleString = #"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:#"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:#"\0" intoString:&right];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
RESULTS (for all options)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
NOTE
All of these assume well-formed strings, so you should include your own error checking.
try like this ,
NSString *sampleString = #"[abc]000";
NSString *pNRegex = #"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(#"success:%i",check);
if success comes as 1 then you can perform the action for separating string into array.

Extract a 8 digit number from string of variable size

I have a string of undetermined size which contains a 8 digit number. Example:
This is 123456 a string
This is a new string 123456
123456 This is another string
How can I extract the integer value of such number?
NSString has an instance method -integerValue which returns the integer value extracted from the string's contents. So [#"123456" integerValue] will return 123456.
I think what you want is an NSScanner. Have the scanner scan up to the first occurrence of the decimalDigitCharacterSet and then use scanInteger: to get the NSInteger value it finds.
You can use regular expressions to pull numbers of any given format out of a string. If you just wanted to grab one integer from any given string (in this case, the first integer):
NSString* str = #"This is 123456 a string";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#".*?(\\d+).*?" options:NULL error:nil];
NSArray* results = [regex matchesInString:str options:NULL range:NSMakeRange(0, [str length])];
NSString* str2 = [str substringWithRange:[(NSTextCheckingResult*)[results objectAtIndex:0] rangeAtIndex:1]];
NSLog(#"%#",str2);
NSInteger intResult = [str2 integerValue];
Extract a number of the given digits from a string of undeterminate length.
#import <Foundation/Foundation.h>
NSNumber* numberFromStringWithDigits(NSString* string, NSUInteger digits)
{
NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *allowed = [NSCharacterSet decimalDigitCharacterSet];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:allowed intoString:&buffer]) {
if ([buffer length]==digits){
return [NSNumber numberWithInt:[buffer integerValue]];
}
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
return nil;
}
int main(int argc, char *argv[]) {
#autoreleasepool {
NSString *url = #"http://garb23age.com/x555xx/xx12345678xxxxxx";
NSDate *startTime = [NSDate date];
NSNumber *n = numberFromStringWithDigits(url,8);
NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
NSLog(#"%# in %f seconds",n,-elapsedTime); // 12345678 in 0.000188 seconds
}
}
#Bri An C: probably what you want is to extract the parameterString of the NSURL. Maybe you should post the URL to ask for alternate solutions.

NSString to fixed length char array conversion

I am having a struct which contains a char array like this:
char name[10];
Now I need a way to convert NSString to this type of string.
I already can convert this string to a NSString:
NSString *string = [[NSString alloc] initWithBytes:name length:10
encoding:NSASCIIStringEncoding];
You can do this with getCString:maxLength:encoding: method of NSString:
char name[10];
NSString *s = #"Hello";
[s getCString:name maxLength:10 encoding:NSASCIIStringEncoding];
the full conversion process back and forth:
// from NSString through char* to NSString again
NSString *text = #"long text or short";
const char *constName = [text UTF8String];
char *name = malloc(sizeof(unichar) * text.length + 1);
memcpy(name, constName, sizeof(unichar) * text.length);
NSString *fromChar = [NSString stringWithUTF8String:name];
NSLog(#"%#", fromChar);
free(name);

Get a char from NSString and convert to int

In C# I can convert any char from my string to integer in the following manner
intS="123123";
int i = 3;
Convert.ToInt32( intS[i].ToString());
What is the shortest equivalent of this code in Objective-C ?
The shortest one line code I've seen is
[NSNumber numberWithChar:[intS characterAtIndex:(i)]]
Many interesting proposals, here.
This is what I believe yields the implementation closest to your original snippet:
NSString *string = #"123123";
NSUInteger i = 3;
NSString *singleCharSubstring = [string substringWithRange:NSMakeRange(i, 1)];
NSInteger result = [singleCharSubstring integerValue];
NSLog(#"Result: %ld", (long)result);
Naturally, there is more than one way to obtain what you are after.
However, As you notice yourself, Objective-C has its shortcomings. One of them is that it does not try to replicate C functionality, for the simple reason that Objective-C already is C. So maybe you'd be better off just doing what you want in plain C:
NSString *string = #"123123";
char *cstring = [string UTF8String];
int i = 3;
int result = cstring[i] - '0';
NSLog(#"Result: %d", result);
It doesn't explicitly have to be a char. Here is one way of doing it :)
NSString *test = #"12345";
NSString *number = [test substringToIndex:1];
int num = [number intValue];
NSLog(#"%d", num);
Just to provide a third option, you can use NSScanner for this too:
NSString *string = #"12345";
NSScanner *scanner = [NSScanner scannerWithString:string];
int result = 0;
if ([scanner scanInt:&result]) {
NSLog(#"String contains %i", result);
} else {
// Unable to scan an integer from the string
}