NSString append WhiteSpace for every 4 Character - ios

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;
}

Related

How to convert a string into hex value and get string back from hex value

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;
}

Objective-C hashtag/tags autocomplete implementation

I was looking into implementing hashtag autocomplete with objective-C as shown in the picture
I found it a bit difficult than expected. I'm looking more specific implementation for adding and deleting hashtags. For example, the hashtag should be deleted as a whole at once. I was wondering if anyone has similar experience implemented it and if there's a more efficient way implemented it. Thanks
I ended up writing some functions that I feel is a bit ugly but it works. Maybe there are some more efficient ways to implement it.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//user is a singleton instance
User *user = [User sharedUser];
user.autocompleteTableView.hidden = NO;
int identifiedTagsStringLength = [self.identifiedTagsString length];
int cursorLocation = range.location;
//insert characters
if (range.location >= identifiedTagsStringLength) {
NSString *newSearch =#"";
NSRange newRange;
if(identifiedTagsStringLength != 0) {
newSearch = [urlField.text substringFromIndex:identifiedTagsStringLength];
newRange = NSMakeRange(range.location - identifiedTagsStringLength, 0);
}
else {
newSearch = textField.text;
newRange = range;
}
NSString *substring = [NSString stringWithString:newSearch];
substring = [substring stringByReplacingCharactersInRange:newRange withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
if (cursorLocation > currentTagsRange) {
currentTagsRange = cursorLocation;
}
}
//delete tags
else {
if ([self.ranges count] != 0 && cursorLocation < currentTagsRange) {
int rangeLength = [self.ranges count];
int toBeRemovedIndex = 0;
for (int i = 0; i< rangeLength; i++) {
if (cursorLocation >= [[self.ranges objectAtIndex:i][0] intValue]
&& cursorLocation <= [[self.ranges objectAtIndex:i][1] intValue]) {
toBeRemovedIndex = i;
}
}
[self.tags removeObjectAtIndex:toBeRemovedIndex];
[self updateRanges];
NSString *outputString = #"";
for (NSString *tag in self.tags) {
outputString = [NSString stringWithFormat:#"%##%# ", outputString,
tag];
}
urlField.text = outputString;
self.identifiedTagsString = urlField.text;
currentTagsRange = [outputString length] - 1;
}
}
return YES;
}
- (void)updateRanges {
self.ranges = [[NSMutableArray alloc] init];
int startIndex = 0;
for (NSString *tag in self.tags) {
startIndex = [self.ranges count] == 0 ? 0 : [[self.ranges lastObject][1] intValue] + 1;
int tagLength = [tag length];
NSArray *range = [NSArray arrayWithObjects:[NSNumber numberWithInt:startIndex], [NSNumber numberWithInt:startIndex + tagLength + 1], nil];
[self.ranges addObject: range];
}
}
#pragma mark UITableViewDataSource methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if (self.identifiedTagsString == NULL) {
self.identifiedTagsString = #"";
}
[self.tags addObject: selectedCell.textLabel.text];
[self updateRanges];
NSString *output = #"";
for (NSString *tag in self.tags) {
output = [NSString stringWithFormat:#"%##%# ", output, tag];
}
urlField.text = output;
User *user = [User sharedUser];
user.autocompleteTableView.hidden = YES;
self.identifiedTagsString = urlField.text;
currentTagsRange = [urlField.text length];
}

Find the highest repeated character in string and the count of the repeated character

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.

Generate a random alphanumeric String in ios

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;
}`

How can i calculate the total number of words and character in textView? [duplicate]

This question already has answers here:
Objective-C: -[NSString wordCount]
(7 answers)
Closed 9 years ago.
i am using the following code to calculate the total number of words
-(NSInteger) getTotalWords{
NSLog(#"Total Word %lu",[[_editor.attributedText string]length]);
if ([[_editor.attributedText string]length]==0) {
return 0;
}
NSString *str =[_editor textInRange:[_editor textRangeWithRange:[self visibleRangeOfTextView:_editor]]];
NSInteger sepWord = [[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsSeparatedByString:#" "] count];
sepWord += [[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsSeparatedByString:#"\n"] count];
sepWord=sepWord-2;
return sepWord;
}
and here is the code for the total character
-(NSInteger) getTotalChars{
NSString *str =[_editor textInRange:[_editor textRangeWithRange:[self visibleRangeOfTextView:_editor]]];
NSLog(#"%#",str);
NSInteger charCount= [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length];
return charCount=charCount-1;
}
But i m not getting the perfect count when i enter more than two lines. it takes new line as word..
please help..!!!
If you really want to count words (i.e. "foo,bar" should count as 2 words with
6 characters) then
you can use the NSStringEnumerationByWords option of enumerateSubstringsInRange,
which handles all the white space and word separators automatically:
NSString *string = #"Hello world.\nfoo,bar.";
__block int wordCount = 0;
__block int charCount = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
wordCount += 1;
charCount += substringRange.length;
}];
NSLog(#"%d", wordCount); // Output: 4
NSLog(#"%d", charCount); // Output: 16
You could simply do:
NSString *text = #"Lorem ...";
NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSInteger wordCount = [words count];
NSInteger characterCount = 0;
for (NSString *word in words) {
characterCount += [word length];
}
once try like this,
NSString *string = #"123 1 2\n234\nponies";
NSArray *chunks = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" \n"]];
NSLog(#"%d",[chunks count]);
for word count...
NSString *str = #"this is a sample string....";
NSScanner *scanner = [NSScanner scannerWithString:str];
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSCharacterSet *nonWhitespace = [whiteSpace invertedSet];
int wordcount = 0;
while(![scanner isAtEnd])
{
[scanner scanUpToCharactersFromSet:nonWhitespace intoString:nil];
[scanner scanUpToCharactersFromSet:whitespace intoString:nil];
wordcount++;
}
int characterCount = 0;
For getting word count use -
NSArray *array = [txtView.text componentsSeparatedByString:#" "];
int wordCount = [array count];
for(int i = 0; i < [array count]; i++){
characterCount = characterCount + [[array objectAtIndex:i] length];
}
NSLog(#"characterCount : %i",characterCount);
NSLog(#"wordCount : %i",wordCount);
str = textView.text;
NSArray *wordArray = [str componentsSeparatedByString:#" "];
int wordCount = [wordArray count];
int charCount=0;
for (int i=0 ; i < [wordArray count]; i++)
{
charCount = charCount + [[wordArray objectAtIndex:0] length];
}

Resources