I got an NSString containing a hex value which I would like to convert in ASCII. How can I do this?
NSString * hexString = // some value
NSString * asciiString = // ? convert hexString to ASCI somehow
INCORRECT APPROACH THAT I TRIED:
I tried the following approach that I found on a similar question but it did not work for me:
NSData *_data = [hexString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableString *_string = [NSMutableString stringWithString:#""];
for (int i = 0; i < _data.length; i++) {
unsigned char _byte;
[_data getBytes:&_byte range:NSMakeRange(i, 1)];
if (_byte >= 32 && _byte < 127) {
[_string appendFormat:#"%c", _byte];
} else {
[_string appendFormat:#"[%d]", _byte];
}
}
asciiString = _string; // Still shows the same as before..
this works for me:
NSString * str = #"312d4555";
NSMutableString * newString = [[NSMutableString alloc] init];
int i = 0;
while (i < [str length]){
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:#"%c", (char)value];
i+=2;
}
NSLog(#"%#", newString);
output is: hello
Related
I have a scenario where i want to convert a string into HexValue and fetch string from HexValue
For e.g i have a string with value '33' in it . So when i convert it to hex i get the result as '21' and when i convert '21' which is the hex value back to string i should get '33' back as the output.
Following is the code which i have done for converting string into hex
+ (NSString *) hexValue:(NSString *)str {
return [NSString stringWithFormat:#"%lX",
(unsigned long)[str integerValue]];
}
so when i pass '33' to this method it returns '21' which is correct
but the problem is i want to retrieve '33' back from '21'
Following is the code
+ (NSString *) unHexValue:(NSString *)str {
return [NSString stringWithFormat:#"%#",str];
}
but this does not return the expected value which is '33'. Instead it returns 21 only.
It is working for me and able to fetch same result.Hope it will help you.
NSString *strHex = [self hexfromString:#"33"];
NSString *newStr = [self stringFromHexString:strHex];
// Hex from String
- (NSString *)hexfromString:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
// [hexString [NSString stringWithFormat:#"%02x", chars[i]]]; /*previous input*/
[hexString appendFormat:#"%02x", chars[i]]; /*EDITED PER COMMENT BELOW*/
}
free(chars);
return hexString;
}
// string From HexString
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%c", decimalValue];
}
return string;
}
I have a NSString like this
#"1,2,3,4,5,6,7,"
I want to count how many numbers are there in this string. How can I do that.
pls help me
Thank you
NSString *numberString = #"1,2,3,4,5,6,7";
NSArray *numberArray = [numberString componentsSeparatedByString:#","];
NSInteger count = numberArray.count;
Use the below code to get Number count in your string as below.
NSString *str = #"1,2,3,5,6,7,3";
BOOL valid;
int count = 0;
for (int i = 0; i < str.length; i++)
{
char chr = [str characterAtIndex:i];
NSString* string = [NSString stringWithFormat:#"%c" , chr];
NSCharacterSet *alphaNums = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:string];
valid = [alphaNums isSupersetOfSet:inStringSet];
if (!valid)
{
}
else{
count ++;
}
}
NSLog(#"=%d",count);
Your Output is :
I have a string like #"1234123412341234", i need to append space between every 4 chars like.
#"1234 1234 1234 1234"
i.e, I need a NSString like Visa Card Type. I have tried like this but i didn't get my result.
-(void)resetCardNumberAsVisa:(NSString*)aNumber
{
NSMutableString *s = [aNumber mutableCopy];
for(int p=0; p<[s length]; p++)
{
if(p%4==0)
{
[s insertString:#" " atIndex:p];
}
}
NSLog(#"%#",s);
}
Here's a unicode aware implementation as a category on NSString:
#interface NSString (NRStringFormatting)
- (NSString *)stringByFormattingAsCreditCardNumber;
#end
#implementation NSString (NRStringFormatting)
- (NSString *)stringByFormattingAsCreditCardNumber
{
NSMutableString *result = [NSMutableString string];
__block NSInteger count = -1;
[self enumerateSubstringsInRange:(NSRange){0, [self length]}
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound)
return;
count += 1;
if (count == 4) {
[result appendString:#" "];
count = 0;
}
[result appendString:substring];
}];
return result;
}
#end
Try it with this test string:
NSString *string = #"ab 😗😌 132487 387 e e e ";
NSLog(#"%#", [string stringByFormattingAsCreditCardNumber]);
The method works with non-BMP characters (i.e. emoji) and handles existing white space.
Your code is pretty close, however a better semantic for the method is to return a new NSString for any given input string:
-(NSString *)formatStringAsVisa:(NSString*)aNumber
{
NSMutableString *newStr = [NSMutableString new];
for (NSUInteger i = 0; i < [aNumber length]; i++)
{
if (i > 0 && i % 4 == 0)
[newStr appendString:#" "];
unichar c = [aNumber characterAtIndex:i];
[newStr appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return newStr;
}
You should do like this:
- (NSString *)resetCardNumberAsVisa:(NSString*)originalString {
NSMutableString *resultString = [NSMutableString string];
for(int i = 0; i<[originalString length]/4; i++)
{
NSUInteger fromIndex = i * 4;
NSUInteger len = [originalString length] - fromIndex;
if (len > 4) {
len = 4;
}
[resultString appendFormat:#"%# ",[originalString substringWithRange:NSMakeRange(fromIndex, len)]];
}
return resultString;
}
UPDATE:
You code will be right on the first inserting space charactor:
This is your originalString:
Text: 123412341234
Location: 012345678901
Base on your code, on the first you insert space character, you will insert at "1" (with location is 4)
And after that, your string is:
Text: 1234 12341234
Location: 0123456789012
So, you see it, now you have to insert second space charater at location is 9 (9%4 != 0)
Hope you can fix your code by yourself!
The code snippet from here do what do you want:
- (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string
andPreserveCursorPosition:(NSUInteger *)cursorPosition
{
NSMutableString *stringWithAddedSpaces = [NSMutableString new];
NSUInteger cursorPositionInSpacelessString = *cursorPosition;
for (NSUInteger i=0; i<[string length]; i++) {
if ((i>0) && ((i % 4) == 0)) {
[stringWithAddedSpaces appendString:#" "];
if (i < cursorPositionInSpacelessString) {
(*cursorPosition)++;
}
}
unichar characterToAdd = [string characterAtIndex:i];
NSString *stringToAdd =
[NSString stringWithCharacters:&characterToAdd length:1];
[stringWithAddedSpaces appendString:stringToAdd];
}
return stringWithAddedSpaces;
}
swift3 based on Droppy
func codeFormat(_ code: String) -> String {
let newStr = NSMutableString()
for i in 0..<code.characters.count {
if (i > 0 && i % 4 == 0){
newStr.append(" ")
}
var c = (code as NSString).character(at: i)
newStr.append(NSString(characters: &c, length: 1) as String)
}
return newStr as String
}
Please make sure that your string length should times by 4.
This solution will insert on the right hand side first.
- (NSString*) fillWhiteGapWithString:(NSString*)source
{
NSInteger dl = 4;
NSMutableString* result = [NSMutableString stringWithString:source];
for(NSInteger cnt = result.length - dl ; cnt > 0 ; cnt -= dl)
{
[result insertString:#" " atIndex:cnt];
}
return result;
}
I have an
NSString *str=#"123456789123456789123456";
My new string should be
NSString *newStr =#"1234 5678 9123 4567 8912 3456";
Can any one help me
Thanks in Advance
You can use this..
NSMutableArray *subStrings = [NSMutableArray array];
NSRange range = {0,subStrLength};
for(int i=0;i< [str length]; i+= subStrLength)
{
range.location = i;
[subStrings addObject:[str substringWithRange:range];
}
Update: NSString *strWithSpace = [subStrings componentsJoinedByString:#" "];
NSString *str=#"123456789123456789123456";
NSMutableString *mutableStr = [str mutableCopy];
for (int i = 4; i < mutableStr.length; i += 5) {
[mutableStr insertString:#" " atIndex:i];
}
How to Generate a random non-repeated(without repeating same alphabet) alphanumeric string from a given String in ios?
The following function will take a string and randomise it, usually each character from the input string only once:
- (NSString *)randomizeString:(NSString *)str
{
NSMutableString *input = [str mutableCopy];
NSMutableString *output = [NSMutableString string];
NSUInteger len = input.length;
for (NSUInteger i = 0; i < len; i++) {
NSInteger index = arc4random_uniform((unsigned int)input.length);
[output appendFormat:#"%C", [input characterAtIndex:index]];
[input replaceCharactersInRange:NSMakeRange(index, 1) withString:#""];
}
return output;
}
-(NSString *)randomStringWithLength: (int) len
{
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++)
{
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}`