Remove characters before dot - ios

Im parsing html and now i got an NSString object that output like that:
imageName is 4tmp.jpg
imageName is 5tmp.jpg
imageName is 6tmp.jpg
imageName is 7tmp.jpg
imageName is 8tmp.jpg
imageName is 9tmp.jpg
And so on.
My code look like:
TFHpple *dataParseer = [TFHpple hppleWithHTMLData:data];
// 3
NSString *dataXpathQueryString = #"//head/title";
NSArray *dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
TFHppleElement *element = dataNodes[0];
if ([element.text hasPrefix:#"Index of"]) {
dataXpathQueryString = #"//tr/td/a";
dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
for (TFHppleElement *element in dataNodes){
NSString *imageName = [element objectForKey:#"href"];
NSLog(#"imageName is %#", imageName);
}
What i want is, remove characters before dot. So i can further concatenate it to correct url. How could i do that with NSString? Is there any method that can check characters before special symbol?

I'm not quite sure what exactly you want to get, but there are several ways to get values from string.
If you are working with path structures you can do something like this.
NSString *path = #"4tmp.jpg";
NSLog(#"1- %#",path.lastPathComponent);
NSLog(#"2- %#",[path.lastPathComponent stringByDeletingPathExtension]);
NSLog(#"3- %#",path.pathExtension);
Which will output something like
1- 4tmp.jpg
2- 4tmp
3- jpg
This will work obviously for more complex paths like "something/4tmp.jpg" in those cases the output will be the same as the one above

NSArray* stringComponents = [imageName componentsSeparatedByString:#"."];
imageName = [stringComponents objectAtIndex:1];

Related

Replace multiple placeholders in string

What I am looking to do is use placeholders in a string and replace the placeholders with data specific to the user. I can setup the placeholders to be anything so basically I am looking to do the following:
Setup placeholders in a string (up to 4 placeholders)
Replace those placeholders with strings I specify
Here is what I have. I currently have a url that has a set of placeholders like so. http://example.com/resource?placeholder1=placeholder2 or http://placeholder1:placeholder2#example.com/something?placeholder3
How do I properly label the placeholders and replace them?
Thank you in advance for any help.
You can use the stringByReplacingOccurrencesOfString method as below
NSString *strUrl = #"http://example.com/resource?placeholder1=placeholder2";
strUrl = [strUrl stringByReplacingOccurrencesOfString:#"placeholder1" withString:#"value1"];
strUrl = [strUrl stringByReplacingOccurrencesOfString:#"placeholder2" withString:#"key1"];
Quote : "I want to replace placeholder1 with an NSString I have already created called value1 and placeholder2 with an NSString called key1."
NSString *mainUrl = "http://example.com/resource";
NSString *string1 = "value1";
NSString *string2 = "value2";
Now change your URL:
NSString *newURL = [NSString NSStringWithFormat:#"%#?%#=%#",mainUrl,string1,string2];
This will generate newURL : http://example.com/resource?value1=value2
This might help you.
#define placeHolder1 #"<>p1p1p1<>"
#define placeHolder2 #"<>p2p2p2<>"
And place this in a function of yours where you want to replace strings
NSString * string = [NSString stringWithFormat:#"http://example.com/resource?%#=%#",placeHolder1,placeHolder2];
NSLog(#"string %#",string);
NSString * replacerForP1 = #"123";
NSString * replacerForP2 = #"741";
string = [string stringByReplacingOccurrencesOfString:placeHolder1
withString:replacerForP1];
string = [string stringByReplacingOccurrencesOfString:placeHolder2
withString:replacerForP2];
NSLog(#"string %#",string);
It would be best to keep your placeholder strings in the constants defined somewhere. And ofcourse the replacement of those placeholders will be dynamic as you said so cannot make them constants.
Tell me if this helps or if you require further assistance in the matter.

iOS: Create String from Variable and string combined

I need to concatenate a string and a variable together - I kind of find lots of examples of adding a string prior to a variable but not the other way round - how do I do this?
NSString *theImage = [[self.detailItem valueForKey:#" resimagefiletitle"] description], #"'add on the end";
Something like this:
NSString *theImage = [NSString stringWithFormat:#"%# %#",[self.detailItem valueForKey:#" resimagefiletitle"], #"'add on the end"];
Or:
NSString *theImage = [NSString stringWithFormat:#"%# add on the end",[self.detailItem valueForKey:#" resimagefiletitle"]];
Try this
NSString *theImage = [NSString stringWithFormat:#"%# '>",[[self.detailItem valueForKey:#"resimagefiletitle"] description]];
Here I am considering [[self.detailItem valueForKey:#"resimagefiletitle"] description] gives NSString
We can concat diffrent type of datatypes into string by mention the format for it.
like if your want to concat two or more strings together then you can use the following code:
NSString *NewString = [NSString stringWithFormat:#"%#%#",#"This Is",#"way to concate string"];
and if your want concat integer value then you can mention the data format for it "%i".
eg:
int OutOf = 150;
NSString *NewString = [NSString stringWithFormat:#"%#%i",#"I got 100 out of ",OutOf];
this may help you.

remove append strings

I have an nsarray with strings like this,
albumname/song42.mp3
albumname/song43.mp3 etc .
I want to remove the string "album name" and ".mp3" from the above array,and display it in a tableview as follows ,
song42
song43
then in the DidSelectRow ,i want to add the string
"http://www.domain.com/albumname/" and ".mp3" to the indepath.row element .
fo eg :
if user selects song42 in tableview ,then it must create a string like this "http://www.domain.com/albumname/song42.mp3"
How to do this ?
- [NSString stringByDeletingPathExtension] <--- This to remove
+ [NSString stringWithFormat:] <--- And this to recreate
EDIT My mistake, you first need to do this before you call the first method:
NSString *lastPath = [string lastPathComponent]; //song43.mp3
NSString *tableString = [lastPath stringByDeletingPathExtension]; //song43
You can use lastPathComponent and stringByDeletingPathExtension methods:
NSMutableArray *songs = [NSArray arrayWithCapacity:[sourceArray count]];
for (NSString *filename in sourceArray) {
[songs addObject:[[filename lastPathComponent] stringByDeletingPathExtension]];
}
use the String method componentsSeparatedByString first separate the strings using / and then . and discard what you don't need.
NSString *str="albumname/song42.mp3";
NSArray *mainStrArray = [str componentsSeparatedByString:#"/"];
NSArray remainingStrArray=[[mainStrArray objectAtIndex:1]componentsSeparatedByString:#"."];
NSString *result=[remainingStrArray objectAtIndex:0]; //here you have song42
You can use, as :
NSString *str = #"album name/song43.mp3";
str=[[str componentsSeparatedByString:#"/"][1]componentsSeparatedByString:#".mp3"][0];
NSLog(#"->%#",str); //song43
NSString *file = #"albumname/song42.mp3";
NSString *name = [[[[file componentsSeparatedByString:#"/"] objectAtIndex:1] componentsSeparatedByString:#"."] objectAtIndex:0];

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

Convert float to NSString using custom format? ("xx:yy")

I'm getting a JSON string back from a web service I'm using, one of the items is a float, which is formatted like this: "1.2".
But I actually want to make it show like a time number, so like this: "01:20".
What would be the easiest way of doing this?
I thought about converting the float to a string and then splitting it into 2 pieces
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
NSArray *tmpArr = [timeValue componentsSeparatedByString:#"."];
NSString *tmpFirst = (NSString *)[tmpArr objectAtIndex:0];
NSString *tmpSecond = (NSString *)[tmpArr objectAtIndex:0];
But somehow when I convert it, it returns me a negative number
NSLog(#"timeValue: %#", timeValue);
timeValue: -1.99
I think the problem is in this line.
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
I think timeValue is of type NSString if not then why are you using same variable twice.
It should be like
timeValueString = [NSString stringWithFormat:#"%.2f", timeValueFloat];

Resources