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;
}`
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 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
I am trying to replace multiple character found in a string at once not using stringByReplacingOccurrencesOfString. So if my string is: #"/BKL_UO+C-" I what to change / to _ ; - to +; + to -; _ to /.
In my code I have tried to do this by applying for each of the signs that I want to replace first the stringByReplacingOccurrencesOfString and save it as a new string and created an NSArray of chars with them. Compared the differences and save them in another array where I push all the differences from all 4 arrays. Then apply all differences to the initial string.
Initial hash string is: #"lRocUK/Qy+V2P3yDhCd74RvHjCDzlTfrGMolZZE0pcQ"
Expected result: #"lRocUK_Qy-V2P3yDhCd74RvHjCDzlTfrGMolZZE0pcQ"
NSMutableArray *originalHashArrayOfCharFromString = [NSMutableArray array];
for (int i = 0; i < [hash length]; i++) {
[originalHashArrayOfCharFromString addObject:[NSString stringWithFormat:#"%C", [hash characterAtIndex:i]]];
}
//1 change
NSString *backslashRplecedInHashString = hash;
backslashRplecedInHashString = [backslashRplecedInHashString stringByReplacingOccurrencesOfString:#"/" withString:#"_"];
NSMutableArray *hashConvertBackslashToUnderline = [NSMutableArray array];
for (int i = 0; i < [hash length]; i++) {
[hashConvertBackslashToUnderline addObject:[NSString stringWithFormat:#"%C", [backslashRplecedInHashString characterAtIndex:i]]];
}
//2 change
NSString *minusRplecedInHashString = hash;
minusRplecedInHashString = [minusRplecedInHashString stringByReplacingOccurrencesOfString:#"-" withString:#"+"];
NSMutableArray *hashConvertMinusToPlus = [NSMutableArray array];
for (int i = 0; i < [hash length]; i++) {
[hashConvertMinusToPlus addObject:[NSString stringWithFormat:#"%C", [minusRplecedInHashString characterAtIndex:i]]];
}
//3 change
NSString *underlineRplecedInHashString = hash;
underlineRplecedInHashString = [underlineRplecedInHashString stringByReplacingOccurrencesOfString:#"_" withString:#"/"];
NSMutableArray *hashConvertUnderlineToBackslash = [NSMutableArray array];
for (int i = 0; i < [hash length]; i++) {
[hashConvertUnderlineToBackslash addObject:[NSString stringWithFormat:#"%C", [underlineRplecedInHashString characterAtIndex:i]]];
}
//4 change
NSString *plusRplecedInHashString = hash;
plusRplecedInHashString = [plusRplecedInHashString stringByReplacingOccurrencesOfString:#"+" withString:#"-"];
NSMutableArray *hashConvertPlusToMinus = [NSMutableArray array];
for (int i = 0; i < [hash length]; i++) {
[hashConvertPlusToMinus addObject:[NSString stringWithFormat:#"%C", [plusRplecedInHashString characterAtIndex:i]]];
}
NSMutableArray *tempArrayForKey = [[NSMutableArray alloc] init];
NSMutableArray *tempArrayForValue = [[NSMutableArray alloc] init];
int possitionInTempArray = 0;
//Store all changes of original array in a temp array
//1 replace
for (int countPosssition = 0 ; countPosssition < [hash length]; countPosssition++) {
if ([originalHashArrayOfCharFromString objectAtIndex:countPosssition] != [hashConvertBackslashToUnderline objectAtIndex:countPosssition]) {
[tempArrayForValue addObject:[hashConvertBackslashToUnderline objectAtIndex:countPosssition]];
[tempArrayForKey addObject:[NSNumber numberWithInt:countPosssition]];
possitionInTempArray++;
}
}
//2 replace
for (int countPosssition = 0 ; countPosssition < [hash length]; countPosssition++) {
if ([originalHashArrayOfCharFromString objectAtIndex:countPosssition] != [hashConvertMinusToPlus objectAtIndex:countPosssition]) {
[tempArrayForValue addObject:[hashConvertMinusToPlus objectAtIndex:countPosssition]];
[tempArrayForKey addObject:[NSNumber numberWithInt:countPosssition]];
possitionInTempArray++;
}
}
//3 replace
for (int countPosssition = 0 ; countPosssition < [hash length]; countPosssition++) {
if ([originalHashArrayOfCharFromString objectAtIndex:countPosssition] != [hashConvertUnderlineToBackslash objectAtIndex:countPosssition]) {
[tempArrayForValue addObject:[hashConvertUnderlineToBackslash objectAtIndex:countPosssition]];
[tempArrayForKey addObject:[NSNumber numberWithInt:countPosssition]];
possitionInTempArray++;
}
}
//4 replace
for (int countPosssition = 0 ; countPosssition < [hash length]; countPosssition++) {
if ([originalHashArrayOfCharFromString objectAtIndex:countPosssition] != [hashConvertPlusToMinus objectAtIndex:countPosssition]) {
[tempArrayForValue addObject:[hashConvertPlusToMinus objectAtIndex:countPosssition]];
[tempArrayForKey addObject:[NSNumber numberWithInt:countPosssition]];
possitionInTempArray++;
}
}
NSLog(tempArrayForKey.debugDescription);
NSLog(tempArrayForValue.debugDescription);
// use the them array to submit changes
for (int count = 0; count < tempArrayForKey.count; count++) {
[originalHashArrayOfCharFromString setObject:[tempArrayForValue objectAtIndex:count] atIndexedSubscript:(int)[tempArrayForKey objectAtIndex:count]];
}
[hash setString:#""];
//Reassemble the hash string using his original array that sufferet modificvations
for (int count = 0; count<originalHashArrayOfCharFromString.count; count++) {
[hash appendString:[NSString stringWithFormat:#"%#", [originalHashArrayOfCharFromString objectAtIndex:count]]];
}
NSLog(hash);
What if you temporarily swapped out the occurrences to a "temp" character so you wouldn't lose data on the swaps and do something like this:
NSString * initialString = #"lRocUK/Qy+V2P3yDhCd74RvHjCDzlTfrGMolZZE0pcQ";
initialString =[initialString stringByReplacingOccurrencesOfString:#"/" withString:#"^"];
initialString =[initialString stringByReplacingOccurrencesOfString:#"-" withString:#"*"];
initialString =[initialString stringByReplacingOccurrencesOfString:#"+" withString:#"-"];
initialString =[initialString stringByReplacingOccurrencesOfString:#"*" withString:#"+"];
initialString =[initialString stringByReplacingOccurrencesOfString:#"_" withString:#"/"];
initialString =[initialString stringByReplacingOccurrencesOfString:#"^" withString:#"_"];
Sorry for my stupid question.
How can i get string return from this following method?
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-(NSString *) randomStringWithLength: (int) len {
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++) {
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}
If I understood your question right, this is what you need to call:
NSString *resultString = [self randomStringWithLength:10];
Note, that [self randomStringWithLength:10] is already a NSString object, so you can use it without declaring variable, e.g.:
NSLog(#"Result = %#;", [self randomStringWithLength:10]);
I need to get the highest repeated character in string and the count of the repeated character.
For that i stored the each character of the string in the array and using the for loops i got each character and the count. is there any other delegate methods to find it to reduce the code?
for example
NSRange theRange = {0, 1}; //{location, length}
NSMutableArray * array = [NSMutableArray array];
for ( NSInteger i = 0; i < [myFormattedString length]; i++) {
theRange.location = i;
[array addObject:[myFormattedString substringWithRange:theRange]];
}
int countForChar = 0;
for (int i=0; i<[array count]; i++) {
NSString *firstCharacter = [array objectAtIndex:i];
for (int j=1; j< [array count]; j++) {
if ([firstCharacter isEqualToString:[array objectAtIndex:j]]) {
countForChar = countForChar + 1;
}
}
NSLog(#"The Charcter is %# The count is %d", firstCharacter, countForChar);
countForChar = 0;
}
Thanks in advance...
Because the string may have more than a char have same most repeat count, so here is my solution:
- (NSArray *)mostCharInString:(NSString *)string count:(int *)count{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
int len = string.length;
NSRange theRange = {0, 1};
for (NSInteger i = 0; i < len; i++) {
theRange.location = i;
NSString *charStr = [string substringWithRange:theRange];
int preCount = 0;
if ([dict objectForKey:charStr]) {
preCount = [[dict objectForKey:charStr] unsignedIntegerValue];
}
[dict setObject:#(preCount+1) forKey:charStr];
}
NSArray *sortValues = [[dict allValues] sortedArrayUsingSelector:#selector(compare:)];
*count = [[sortValues lastObject] unsignedIntegerValue];
return [dict allKeysForObject:#(*count)];
}
How to use and test:
int mostRepeatCount = 0;
NSArray *mostChars = nil;
mostChars = [self mostCharInString:#"aaabbbcccc" count:&mostRepeatCount];
NSLog(#"count:%d char:%#", mostRepeatCount, mostChars);
the result is:
count:4 char:(
c
)
try:
mostChars = [self mostCharInString:#"aaabbbccccdddd" count:&mostRepeatCount];
the result is:
count:4 char:(
d,
c
)
Hope to help you.
Here is my code might be not good enough but I think its the fastest
NSString *myFormattedString = #"oksdflajdsfd";
NSMutableDictionary *lettersCount = [[NSMutableDictionary alloc] init];
for (NSInteger i = 0; i < [myFormattedString length]; i++) {
unichar charAtIndex = [myFormattedString characterAtIndex:i];
NSNumber *countForThisChar = [lettersCount objectForKey:[NSString stringWithFormat:#"%c",charAtIndex]];
int count = 1;
if(countForThisChar) {
count = [countForThisChar integerValue] + 1;
[lettersCount setObject:#(count) forKey:[NSString stringWithFormat:#"%c",charAtIndex]];
} else {
// not added yet, add it with 1 count
[lettersCount setObject:#(count) forKey:[NSString stringWithFormat:#"%c",charAtIndex]];
}
}
// for now the work is O(n)
// ignoring the work of this cycle or consider it as O(1)
NSString *mostFrequentChar = nil;
NSInteger maxCount = 0;
for(NSString *oneChar in lettersCount.keyEnumerator) {
NSNumber *count = [lettersCount objectForKey:oneChar];
if([count integerValue] > maxCount) {
mostFrequentChar = oneChar;
maxCount = [count integerValue];
}
}
NSLog(#"the char %# met for %d times", mostFrequentChar, maxCount);
Remember the search for an object in NsDictionary is O(1) for the average case scenario.
Here is an example that would work correctly with any string and has linear time complexity. This uses the NSCountedSet which can be pretty useful.
NSString* string = #"This is a very wonderful string. Ølsen & ジェイソン";
NSCountedSet* characterCounts = [[NSCountedSet alloc] init];
// This ensures that we deal with all unicode code points correctly
[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characterCounts addObject:substring];
}];
NSString* highestCountCharacterSequence = nil;
NSUInteger highestCharacterCount = 0;
for (NSString* characterSequence in characterCounts) {
NSUInteger currentCount = [characterCounts countForObject:characterSequence];
if (currentCount > highestCharacterCount) {
highestCountCharacterSequence = characterSequence;
highestCharacterCount = currentCount;
}
}
NSLog(#"Highest Character Count is %# with count of %lu", highestCountCharacterSequence, (unsigned long)highestCharacterCount);
Sadly, my silly example string ends up having space characters as the most repeated :)
Every character can be presented by its int value. Make an instance of NSArray with n size (n number of unique characters string can have). Loop through string and add +1 on (int)character index in array at every cycle. When you finish the character with greatest value in array is the highest repeated character.