Filtering string for date - objective-c

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

Related

Objective-C, correctly separate columns in CSV by comma

I have an Excel file that I exported as a CSV file.
Some of the data in the columns also have commas. CSV escapes these by putting the string in the column in quotes (""). However, when I try to parse it in Objective-C, the comma inside the string seperates the data, as if it were a new column.
Here's what I have:
self.csvData = [NSString stringWithContentsOfURL:file encoding:NSASCIIStringEncoding error:&error];
//This is what the data looks like:
//"123 Testing (Sesame Street, Testing)",Hello World,Foo,Bar
//Get rows
NSArray *lines = [self.csvData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//Get columns
NSArray *columns = [[lines objectAtIndex:0] componentsSeparatedByString:#","];
//Show columns
for (NSString *column in columns) {
NSLog(#"%#", column);
}
//Console shows this:
"123 Testing (Sesame Street
Testing)"
Hello World
Foo
Bar
Notice how "123 Testing (Sesame Street and Testing)" are output as separate columns. I need these to be one. Any ideas?
Any ideas?
Design an algorithm.
At the start of the input you have one of three possibilities:
You have a " - parse a quoted field
You have a , - handle an empty field
Otherwise - parse a non-quoted field
After parsing if there is any more input left then iterate (loop).
You might start with some variables:
NSUInteger position = 0; // current position
NSUInteger remaining = csvData.length; // left to parse
then enter your loop:
while(remaining > 0)
{
get the next character:
unichar nextChar = [csvData characterAtIndex:position];
Now check if that character is a ", , or something else. You can use an if or a switch.
Let's say it's a comma, then you want to find the position of the next comma. The NSString method rangeOfString:options:range will give you that. The last argument to this method is a range specifying in which part of the string to search for the comma. You can construct that range using NSMakeRange and values derived from position and remaining.
Once you have the next comma you need to extract the field, the substringWithRange: method can get you that.
Finally update position and remaining as required and you are ready for the next iteration.
You'll have to handle a few error cases - e.g. opening quote with no closing quote. Overall it is straight forward.
If you start down this path and it doesn't work ask a new question, showing your code and explaining where you got stuck.
HTH

How split a string by equial parts?

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 )

Reading string from array then changing string and outputting new result

I am trying to grab a string in my array, change nth letter in the string to a ?, then print the result in a textfield. The problem is my NSMutableArray is being stored into a UIPickerView and I think it would be best just to read the string from the PickerView then change the nth char and print the result. I am struggling with how to grab the string from the picker and change the nth letter.
- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (row == 0 ) {
NSString *originalStringTwo = #"%#", *arrayDictionary;
NSRange two = [originalStringTwo rangeOfString:#"2"];
NSString *newStringTwo = [originalStringTwo stringByReplacingCharactersInRange:two withString:#"?"];
_resultLabel.text = newStringTwo;
}
if (row == 1 ) {
NSString *originalStringThree = #"%#", *arrayDictionary;
NSRange three = [originalStringThree rangeOfString:#"3"];
NSString *newStringThree = [originalStringThreestringByReplacingCharactersInRange:three withString:#"?"];
_resultLabel.text = newStringThree;
}
if ( row == 2 ) {
NSString *originalStringFour = #"%#", *arrayDictionary;
NSRange four = [originalStringFour rangeOfString:#"4"];
NSString *newStringFour = [originalStringFour stringByReplacingCharactersInRange:four withString:#"?"];
_resultLabel.text = newStringFour;
}
return 0;
}
That's not how you create an NSRange. Use NSMakeRange instead.
// Range from index 1 with length 1, eg. 2nd character:
NSRange two = NSMakeRange(2, 1);
NSString *newStringTwo = [originalStringTwo stringByReplacingCharactersInRange:two
withString:#"?"];
Note, that it's never a good idea to grab any data from a GUI element (except user input). What if the text field applies custom formatting?
You should keep your data in your array and use that.

count NSMutableArray size till or from a specific word?

I have got an array, I know how to count its elements, but I need to count elements until a specific word:
NSMutableArray *whatBondInFrame;
whatBondInFrame=[NSMutableArray arrayWithObjects:#"red",#"red",#"red",#"gray",#"red",#"ran",#"gray",#"gray",nil];
I know [ whatBondInFrame count] but, let's say I want to know how many elements I have till the first gray or from the word "ran".
How would I get that?
This isn't tested but it should work:
int loc = 0;
for (loc; loc < [array count]; loc++) {
NSString *str = [array objectAtIndex:loc];
if ([str isEqualToString:#"ran"])
break;
}
int length = array.count-loc;
this gives you the count from the first element named ran.
If you want to know how many elements there are before (till) the word 'ran' then replace the last line with
int length = loc
The NSArray method:
- (NSUInteger)indexOfObject:(id)anObject
Will return the index of the first occurrence on an object, so you can do:
NSUInteger firstRanIndex = [whatBondInFrame indexOfObject:#"ran"];
There is a companion method:
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range
Which restricts the search to a given range of the array. There is no method to find the last occurrence, for that you must loop with the above methods.
In conjunction with the count method you can get the numbers you want.

Get longest word from a list of words

Is there a quick method that gets the largest word from an array of words?
NSMutableArray wordlist
Something like the following should do the trick:
NSString *longest = nil;
for(NSString *str in wordlist) {
if (longest == nil || [str length] > [longest length]) {
longest = str;
}
}
I'm not aware of any simpler method.
You could use something like this example to sort an Array (but instead of the 'quality' sort in the example use a length sort on your strings) and then the longest string will be either at the top or at the end (depending on your sorting).
I don't know any objective C myself, but my solution would be to keep an integer 'longest' and a string 'longestWord' and initialise it to 0 and "". Then loop over the list and check if the current word is longer then the 'longest' value. If it is, store the new length and the current word. At the end of the loop, you have the longest word stored in the 'longestWord' variable.
Hope this helps