How to substring an NSString in iOS - 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];
}

Related

How to count characters inside a NSString

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 :

Replace simultaneously multiple char in NSString

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:#"_"];

NSString to char my[16]

I am having NSString like :
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
how can i convert it to char array as shown below:
char keyPtr[16] = {225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45}
can anyone help!
Thanks
NSString *input = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
char output[16];
NSArray *elements = [input componentsSeparatedByString:#","];
NSAssert([elements count] == 16, #"Input has wrong number of elements");
unsigned index = 0;
for (NSString *element in elements) {
int value = [element intValue];
NSAssert(value >= 0 && value <= 255, #"Element is invalid");
output[index++] = (char)value;
}
Note: You probably should be using a int[], and not char[], for output.
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
NSArray *array = [str componentsSeparatedByString:#","];
Then use this in a for loop or something to add to your char array:
char* myLilChar = [[array objectAtIndex:i] UTF8String];
Cheers :)
If you want to be as you said, use below
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45";
NSArray *array = [str componentsSeparatedByString:#","];
unsigned char keyPtr[array.count];
for(int i=0;i<array.count;i++)
keyPtr[i] = (unsigned char)[[array objectAtIndex:i] intValue];

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

Index of a character from the NSString in iOS

I have an NSString for example "This is my question".I want to find all the indices of the character/substring "i" ie In this case If index starts from 0,then I want 2,5,16 as my answer.
The other answer is a bit of an overkill. Why don't you simply iterate over the characters like this:
NSString *x = #"This is my question";
for (NSUInteger i=0;i<[x length];i++)
{
if ([x characterAtIndex:i]=='i')
{
NSLog(#"found: %d", i);
}
}
It outputs exactly your positions:
found: 2
found: 5
found: 16
I'd like suggest my solution. It is like this:
NSString* str = #"This is my question";
NSArray* arr = [str componentsSeparatedByString: #"i"];
NSMutableArray* marr = [NSMutableArray arr];
NSInteger cnt = 0;
for (NSInteger i = 0; i < ([arr count]); i++)
{
NSString* s = [arr objectAtIndex: i];
cnt += [s length];
[marr addObject: [NSNumber numberWithInt: cnt]];
cnt += [#"i" length];
}
NSLog(#"%#", [marr description]);
On console:
2
5
16
I don't know is there any built-in functions available for doing this. You can use this method:
- (NSMutableArray *)indexOfCharacter:(char)c inString:(NSString*)string
{
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
for(int i=0;i<string.length;i++)
{
if(c == [string characterAtIndex:i])
{
[returnArray addObject:[NSNumber numberWithInt:i]];
}
}
return returnArray;
}
Using NSRange and loop and with some string manipulation you can easily do it.
NSString *string = #"This is my question";
NSString *substring = #"i";
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length)
{
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if (foundRange.location != NSNotFound)
{
// found an occurrence of the char
searchRange.location = foundRange.location+foundRange.length;
NSLog(#"Location of '%#' is %d",substring,searchRange.location-1);
}
}
EDIT
Using NSRegularExpression and NSRange you can do like this.
NSString *string = #"This is my question";
NSString *substring = #"i";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:substring
options:0
error:NULL];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [result range];
NSLog(#"Location of '%#' is %d",substring, range.location);
}];
output is
Location of 'i' is 2
Location of 'i' is 5
Location of 'i' is 16
This is my attempt at a no loop code of getting what you want. I coded this blind, meaning not-tested etc. Its basically a recursive function, but I think it gets you the general idea.
- (NSArray *)getAllEyes:(NSString *)s index:(int)index) {
if (!s || s.length <= 0 || index >= s.length) return [NSArray new];
NSRange *r = [s rangeOfString(#"i") options:NSLiteralSearch range:NSMakeRange(index, s.length - index)];
if (r.location == NSNotFound) {
return [NSArray new];
} else {
NSMutableArray *array = [NSMutableArray new];
[array addObject:#(r.location)];
[array addObjectsFromArray:[self getAllEyes:s index:r.location + 1]];
return array;
}
}
// usage:
NSArray *allEyes = [self getAllEyes:#""];
for (NSNumber *n in allEyes) {
NSLog(#"i = %#", n);
}

Resources