How to count characters inside a NSString - ios

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 :

Related

NSString append WhiteSpace for every 4 Character

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

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.

How to substring an NSString in iOS

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

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