How split a string by equial parts? - objective-c

How I can split a string into equal parts and not a character, ie, a string that is 20 characters divided into 5 strings with 2 characters each no matter what kind of character is?
don't work to me [NSString componentsSeparatedByString]: because the characters change randomly.
i'm using objetive-c on xcode 5

This is just an example of what you're probably looking to do. This method assumes the length of the string is evenly divisible by the intended substring length, so having a test string with 20 characters and a substring length of 2, will produce an array with 10 substrings with 2 characters in each. If the test string is 21 characters the 21st char will be ignored. Once again, this is not THE way to do exactly what you want to do (which still isn't totally clear), but it is merely a demonstration of something similar to what you may want to be doing:
// create our test substring (20 chars long)
NSString *testString = #"abcdefghijklmnopqrstu";
// our starting point will begin at 0
NSInteger startingPoint = 0;
// each substring will be 2 characters long
NSInteger substringLength = 2;
// create our empty mutable array
NSMutableArray *substringArray = [NSMutableArray array];
// loop through the array as many times as the substring length fits into the test
// string
for (NSInteger i = 0; i < testString.length / substringLength; i++) {
// get the substring of the test string starting at the starting point, with the intended substring length
NSString *substring = [testString substringWithRange:NSMakeRange(startingPoint, substringLength)];
// add it to the array
[substringArray addObject:substring];
// increment the starting point by the amount of the substring length, so next iteration we
// will start after the last character we left off at
startingPoint += substringLength;
}
The above produced this:
2014-08-23 15:33:41.662 NewTesting[49723:60b] (
ab,
cd,
ef,
gh,
ij,
kl,
mn,
op,
qr,
st )

Related

Objective-C Displaying Numbers as Words Using Math

I have an exercise in my Objective-C book in which I must design a program using only the knowledge the book has given me so far to do so. It tells me to use math to do this not any methods from Objective-C.
What I must do is get any integer from the user and then convert each number to a word.
For example if the user enters: 956
The output must then be:
nine
five
six
I am not the best math student and definitely need help here. I can of course use loops of any kind as well as if statements and basic math operators as well as arrays but no built in methods.
I assume that I need to get each digit separated into its own integer variable and then use switch of if statements to then create the strings and display them but cannot successfully do this.
Please help, thanks!
Here's an example I quickly came up with. See the comments in the code below for an explanation.
//Create an array of number strings. They must be in order starting from 0 so the indexes line up
NSArray *numbers = #[#"zero", #"one", #"two", #"three", #"four", #"five", #"six", #"seven", #"eight", #"nine"];
//Create whatever string you're processing
NSString *numString = #"956";
//Loop through the substrings of the number string
while (numString.length > 0) {
//Get the first character in the string
int currentNum = [[numString substringToIndex:1] intValue];
//Print the number. The number string should be at the index of this value in the array
NSLog(#"%#", numbers[currentNum]);
//Remove everything before the first character
numString = [numString substringFromIndex:1];
}
Output:
nine
five
six
Here is a working example using C (one of your tags):
This one makes use of a char *[] (array of C strings) and ascii values of each char...
char *number[]={"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int main(void)
{
char dig[20];
int len, i;
printf("enter integer: "); //instruction to user
scanf("%s", dig); //read from user
len = strlen(dig);
for(i=0;i<len;i++)
{
if(isdigit(dig[i]))//test to verify good user input (accept only digits)
{
printf("%s\n", number[dig[i]-48]); // 48-57 is range of ASCII values for 0-9
}
}
return 0;
}
Example session:

Reverse a double value

I'm trying to reverse a double value like this:
Input: 1020304050...... Output: 5040302010
the group of 2 digits remain in the same order. So 10 doesn't become 01. or 53 doesn't become 35.
The input will always have even number of digits, so pairing isn't an issue.
The 2 adjacent digits are actually a code number for a function. And I want to maintain that so I can apply that function again.
double temp = 0.0;
double Singlefilter=1;
double reverseString=0;
temp=filtersequence;
while (temp>0)
{
Singlefilter=fmod(temp, 100.00);
temp=temp/100;
reverseString=(reverseString+Singlefilter)*100;
NSLog(#"reversed string of filter %f",reverseString);
}
But I have no idea why this isn't working. This is generating randomly very very big values.
[This question has been replaced by Reverse a double value while maintaining 2 adjacent digits in same format]
You can do it like this:
#import <Foundation/Foundation.h>
#include "math.h"
void outputGroupReversed(double filtersequence)
{
double reverseString = 0.0;
double temp = filtersequence;
while (temp > 0.0)
{
double groupMultiplier = 100.0;
double singleFilter = fmod(temp, groupMultiplier);
temp = floor(temp / groupMultiplier);
reverseString = reverseString * groupMultiplier + singleFilter;
}
NSLog(#"reversed string of filter %f", reverseString);
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
outputGroupReversed(1020304050.0);
}
return 0;
}
This code does not handle input with a fractional part correctly, though.
You're better off just converting it to a string and reversing it.
NSString *inputString = [#(input) stringValue]; // Eg 1230
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [inputString length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[inputString substringWithRange:subStrRange]];
}
double result = [reversedString doubleValue]; // Eg 0321 -> 321
// Go back to NSString to get the missing length
NSString *resultString = [#(result) stringValue]; // Eg. 321
// Multiple by factors of 10 to add zeros
result *= exp(10, [inputString length] - [resultString length]); // 3210
NSLog(#"reversed value %f", result);
Reverse string method from this answer.
If you wish to store 2-digit decimal integers packed together as a single numeric value you would be better of using uint64_t - unsigned long 64 bit integers rather than double. That will store 9 pairs of two decimal digits precisely which appears to be one more than you need (you mention 16 digits in a comment).
As long as the numeric value of the packed pairs is not important, just that you can pack 8 2-digit decimal numbers (i.e. 0 -> 99) into a single numeric value, then you can do better. A 64-bit integer is 8 pairs of 2-hexadecimal digit numbers, or 8 8-bit bytes, so you can store 8 values 0 -> 99 one per byte. Now adding and extracting values becomes bit-shifts (>> & << operators) by 8 and bitwise-or (|) and bitwise-and (&). This at least makes it clear you are packing values in, which divide & remainder do not.
But there is another payoff, your "reverse" operation now becomes a single call to CFSwapInt64() which reverses the order of the bytes.
However having said the above, you really should look at your model and consider another data type for what you are doing - long gone are the days when programs had to pack multiple values into words to save space.
For example, why not just use a (C) array of 8-bit (uint8_t values[8]) integers? If you require you can place that in a struct and pass it around as a single value.

Count number of arbitrary repeating decimal numbers in NSString

In my code, I'm dealing with an NSString that contains an NSNumber value. This NSNumber value could possibly be a repeating decimal number (e.x. 2.333333333e+06) that shortens to "2.333333" in a string format. It could also be a terminating number (e.x. 2.5), negative, or irrational number (2.398571892858...) (only dealing with decimals here)
I need to have a way to figure out if there are the repeating numbers in the string (or the NSNumber, if necessary). In my code, I would have no way to know what the repeating number would be, as it's a result of computations started by the user. I have tried this for loop (see below) that doesn't work the way I want it to, due to my inexperience with string indexing/ranges/lengths.
BOOL repeat = NO; //bool to check if repeating #
double repNum, tempNum; //run in for loop
NSString *repeating = [numVal stringValue]; //string that holds possible repeating #
for (int i = 3; i <= [repeating length]-3; i++) { //not sure about index/length here
if (i == 3) {
repNum = [repeating characterAtIndex:i];
}
tempNum = [repeating characterAtIndex:i];
if (tempNum == repNum) {
repeat = YES;
} else {
repeat = NO;
}
}
This code doesn't work as I'd like it to, mainly because I also have to account for negative dashes in the string and different amounts of numbers (13 1/3 vs. 1 1/3). I've used the modffunction to separate the integers from the decimals, but that hasn't worked well for me either.
Thank you in advance. Please let me know if I can clarify anything.
EDIT:
This code works with the finding of different solutions for polynomials (quadratic formula). Hope this helps put it into context. See here. (Example input)
NSNumber *firstPlusSolution, *secondMinusSolution;
NSString *pValueStr, *mValueStr;
firstPlusSolution = -(b) + sqrt(square(b) - (4)*(a)*(c)); //a, b, c: "user" provided
firstPlusSolution /= 2*(a);
secondMinusSolution = -(b) - sqrt(square(b) - 4*(a)*(c));
secondMinusSolution /= 2*(a);
pValueStr = [firstPlusSolution stringValue];
mValueStr = [secondMinusSolution stringValue];
if ([NSString doesString:pValueStr containCharacter:'.']) { //category method I implemented
double fractionPart, integerPart;
fractionPart = modf(firstPlusSolution, &integerPart);
NSString *repeating = [NSString stringWithFormat:#"%g", fractionPart];
int repNum, tempNum;
BOOL repeat = NO;
//do for loop and check for negatives, integers, etc.
}
if ([NSString doesString:mValueStr containCharacter'.']) {
//do above code
//do for loop and check again
}
Use C. Take the fractional part. Convert to a string with a known accuracy. If length of string indicates that last digits are missing, then it does not repeat. Use NSString-UTF8String to convert a string. Get rid of the last digit (may be rounding or actual floating point arithmetic error). Use function int strncmp ( const char * str1, const char * str2, size_t num ) to perform comparison within the string itself. If the result is 8 characters long and the last 2 characters match the first 2 characters, then shall the first 6 characters be considered repeating?
Assuming that fraction knowledge your desire:
• Possibility 1: Use fractions. Input fractions. Compute with fractions. Output fractions. Expand upon one of the many examples of a c++ fraction class if necessary and use it.
• Possibility 2: Choose an accuracy which is much less than double. Make a fraction from the result. Reduce the fraction allowing rounding based upon accuracy.
I suggest use not optimal but easy to write solution
Create NSMutableDictionary that will contain number as key and count of occurrence as value.
You can use componentsSeparatedByString: if numbers in string delimited by known symbol
In loop check valueForKey in dictionary and if need increase value
Last step is analyzing our dictionary and do anything you need with numbers

Filtering string for date

I have a string that looks like this:
"51403074 0001048713 1302130446 TOMTOM101 Order
51403074-3-278065518: ontvangen"
This string is filtered from a array that contains similar strings. This string contains some relevant data and some irrelevant data. The only part of the string that is relevant is:1302130446. This number represents a date and time (yy/mm/dd/hh/mm). Because this part is a date and time its not the same every time.
How can I filter this string so that I will have a string that only contains the relevant part.
Sorry still learning IOS dev.
If the date string will always be the third word you could split the NSString into a word array as
NSString *myString = #"This is a test";
NSArray *myWords = [myString componentsSeparatedByString:#" "];
and then access the third item in the array to get the string you wanted.
EDIT (due to comment): To be sure that you get the correct string from your word array you need a unique identifier for your string. It could be that 'TOMTOM101' always follows the date string or something thing else...
**EDIT 2 (due to need of example code)
NSUInteger counter = 0;
NSUInteger dateStringIndex = 0;
for(NSString *str in myWords) {
counter ++;
if([str isEqualToString:#"TOMTOM101"]) {
dateStringIndex = counter - 1;
//We now know which word is the date number, so we can stop looping.
break;
}
}
(not compiled code)
Seems like the relevant string is 10 characters in length.
If the position of this relevant string is fixed in your original string (comes right after TOMTOM),
then you can do something like this:-
iterate through the length of the original string, and look for a block that is = 'TOMTOM'
while iterating add a counter value for count, update it by 1, whenever you meet a 'space'....aka when you meet the first 'space', add a counter value, say count = 1, then when u meet the 2nd space, update count = 2.. and so on,
when you find TOMTOM, your counter will have a value, say =4, therefore you know date string is located after count is set = 3 and before count is set = 4.
while count = 3 do: extract 'relevant string from original string'. When u come across the next 'space', update count = 4, and hence stop extracting from original string.
All you have to do is separate the original string with one-letter space.
NSString *whatever = #"51403074 0001048713 1302130446 TOMTOM101 Order 51403074-3-278065518: ontvangen"
NSString *mydatestring = [self NthString:whatever :#" " :2];
- (NSString *)NthString:(NSString *)source:(NSString *)part:(NSInteger)i {
if (i >= 0) {
NSArray* components = [source componentsSeparatedByString:part];
return [components objectAtIndex:i];
}
else {
return #"";
}
}

How to extract elements of NSArray and convert them(parseInt) to integer values?

I have a string which is a 13 digit number. I need to separate all the digits and find the sum of the individual digits. How can I do that?
I converted the string to NSArray like this :
NSArray *arrStrDigits = [str13DigitNumber componentsSeparatedByString:#""];
now I want to run a loop and get something like arrStrDigits[i]
I am new to Objective C :(. Please help me out!
Get the individual digits like this:
unichar digitChar = [str13DigitNumber characterAtIndex: someIndex];
// Should put in some validation that you have a digit here
int digit = digitChar - '0';
That just needs to go in a loop where you iterate someIndex from 0 to [str13DigitNumber length]
int total=0;
for(NSString *numberInString in arrStrDigits)
{
total+=[numberInString intValue];
}
Note: I am assuming you have int's in each position of your array.
Note 1: This answer is only related to what you ask (run a loop, nothing else).