I have the following string
NSString *word1=#"hitoitatme";
as you can see, if you were to add a space after every second character, it would be a string of words that contain min/max 2 characters.
NSString *word2=#"hi to it at me";
I want to be able to add a white character space to my string after every 2 characters. How would I go about doing this? So if I have a string such as word1, I can add some code to make it look like word2? I am looking if possible for the most efficient way of doing this.
Thank you in advance
There might be different ways to add white space in the string but one way could be using NSRegularExpression
NSString *originalString = #"hitoitatme";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:#"([a-z])([a-z])" options:0 error:NULL];
NSString *newString = [regexp stringByReplacingMatchesInString:originalString options:0 range:NSMakeRange(0, originalString.length) withTemplate:#"$0 "];
NSLog(#"Changed %#", newString);//hi to it at me
You can do this way:
NSString *word1=#"hitoitatme";
NSMutableString *toBespaced=[NSMutableString new];
for (NSInteger i=0; i<word1.length; i+=2) {
NSString *two=[word1 substringWithRange:NSMakeRange(i, 2)];
[toBespaced appendFormat:#"%# ",two ];
}
NSLog(#"%#",toBespaced);
Related
Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)
First off, I have no control over the text I am getting. Just wanted to put that out there so you know that I can't change the links.
The text I am trying to find links in using NSDataDetector contains the following:
<h1>My main item</h1>
<img src="http://www.blah.com/My First Image Here.jpg">
<h2>Some extra data</h2>
The detection code I am using is this, but it will not find this link:
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
for (NSTextCheckingResult *match in matches)
{
if ([match resultType] == NSTextCheckingTypeLink)
{
NSURL *url = [match URL];
// does some stuff
}
}
Is this a bug with Apple's link detection here, where it can't detect links with spaces, or am I doing something wrong?
Does anyone have a more reliable way to detect links regardless of whether they have spaces or special characters or whatever in them?
I just got this response from Apple for a bug I filed on this:
We believe this issue has been addressed in the latest iOS 9 beta.
This is a pre-release iOS 9 update.
Please refer to the release notes for complete installation
instructions.
Please test with this release. If you still have issues, please
provide any relevant logs or information that could help us
investigate.
iOS 9 https://developer.apple.com/ios/download/
I will test and let you all know if this is fixed with iOS 9.
You could split the strings into pieces using the spaces so that you have an array of strings with no spaces. Then you could feed each of those strings into your data detector.
// assume str = <img src="http://www.blah.com/My First Image Here.jpg">
NSArray *components = [str componentsSeparatedByString:#" "];
for (NSString *strWithNoSpace in components) {
// feed strings into data detector
}
Another alternative is to look specifically for that HTML tag. This is a less generic solution, though.
// assume that those 3 HTML strings are in a string array called strArray
for (NSString *htmlLine in strArray) {
if ([[htmlLine substringWithRange:NSMakeRange(0, 8)] isEqualToString:#"<img src"]) {
// Get the url from the img src tag
NSString *urlString = [htmlLine substringWithRange:NSMakeRange(10, htmlLine.length - 12)];
}
}
I've found a very hacky way to solve my issue. If someone comes up with a better solution that can be applied to all URLs, please do so.
Because I only care about URLs ending in .jpg that have this problem, I was able to come up with a narrow way to track this down.
Essentially, I break out the string into components based off of them beginning with "http:// into an array. Then I loop through that array doing another break out looking for .jpg">. The count of the inner array will only be > 1 when the .jpg"> string is found. I then keep both the string I find, and the string I fix with %20 replacements, and use them to do a final string replacement on the original string.
It's not perfect and probably inefficient, but it gets the job done for what I need.
- (NSString *)replaceSpacesInJpegURLs:(NSString *)htmlString
{
NSString *newString = htmlString;
NSArray *array = [htmlString componentsSeparatedByString:#"\"http://"];
for (NSString *str in array)
{
NSArray *array2 = [str componentsSeparatedByString:#".jpg\""];
if ([array2 count] > 1)
{
NSString *stringToFix = [array2 objectAtIndex:0];
NSString *fixedString = [stringToFix stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
newString = [newString stringByReplacingOccurrencesOfString:stringToFix withString:fixedString];
}
}
return newString;
}
You can use NSRegularExpression to fix all URLs by using a simple regex to detect the links and then just encode the spaces (if you need more complex encoding you can look into CFURLCreateStringByAddingPercentEscapes and there are plenty of examples out there). The only thing that might take you some time if you haven't worked with NSRegularExpression before is how to iterate the results and do the replacing, the following code should do the trick:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"src=\".*\"" options:NSRegularExpressionCaseInsensitive error:&error];
if (!error)
{
NSInteger offset = 0;
NSArray *matches = [regex matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
for (NSTextCheckingResult *result in matches)
{
NSRange resultRange = [result range];
resultRange.location += offset;
NSString *match = [regex replacementStringForResult:result inString:myHTML offset:offset template:#"$0"];
NSString *replacement = [match stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
myHTML = [myHTML stringByReplacingCharactersInRange:resultRange withString:replacement];
offset += ([replacement length] - resultRange.length);
}
}
Try this regex pattern: #"<img[^>]+src=(\"|')([^\"']+)(\"|')[^>]*>" with ignore case ... Match index=2 for source url.
regex demo in javascript: (Try for any help)
Demo
Give this snippet a try (I got the regexp from your first commentator user3584460) :
NSError *error = NULL;
NSString *myHTML = #"<http><h1>My main item</h1><img src=\"http://www.blah.com/My First Image Here.jpg\"><h2>Some extra data</h2><img src=\"http://www.bloh.com/My Second Image Here.jpg\"><h3>Some extra data</h3><img src=\"http://www.bluh.com/My Third-Image Here.jpg\"></http>";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"src=[\"'](.+?)[\"'].*?>" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:myHTML options:0 range:NSMakeRange(0, [myHTML length])];
NSTextCheckingResult *match = [regex firstMatchInString:myHTML options:0 range:NSMakeRange(0, myHTML.length)];
for (NSTextCheckingResult *match in arrayOfAllMatches) {
NSRange range = [match rangeAtIndex:1];
NSString* substringForMatch = [myHTML substringWithRange:range];
NSLog(#"Extracted URL : %#",substringForMatch);
}
In my log, I have :
Extracted URL : http://www.blah.com/My First Image Here.jpg
Extracted URL : http://www.bloh.com/My Second Image Here.jpg
Extracted URL : http://www.bluh.com/My Third-Image Here.jpg
You should not use NSDataDetector with HTML. It is intended for parsing normal text (entered by an user), not computer-generated data (in fact, it has many heuristics to actually make sure it does not detect computer-generated things which are probably not relevant to the user).
If your string is HTML, then you should use an HTML parsing library. There are a number of open-source kits to help you do that. Then just grab the href attributes of your anchors, or run NSDataDetector on the text nodes to find things not marked up without polluting the string with tags.
URLs really shouldn't contain spaces. I'd remove all spaces from the string before doing anything URL-related with it, something like the following
// Custom function which cleans up strings ready to be used for URLs
func cleanStringForURL(string: NSString) -> NSString {
var temp = string
var clean = string.stringByReplacingOccurrencesOfString(" ", withString: "")
return clean
}
Earlier I had string as 1,2,3,,5,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,5,6,7
Now I have string as below.
1,2,3,,,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,,6,7
Is there way where I can replace all double comma by single comma.
I know I can do it using for loop or while loop, but I want to check is there any other way?
for (int j=1;j<=100;j++) {
stringByReplacingOccurrencesOfString:#",," withString:#","]]
}
NSString *string = #"1,2,3,,,6,7";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",{2,}" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#","];
NSLog(#"%#", modifiedString);
This will match any number of , present in the string. It's future proof :)
Not the perfect solution, but what about this
NSString *string = #"1,2,3,,,6,7";
NSMutableArray *array =[[string componentsSeparatedByString:#","] mutableCopy];
[array removeObject:#""];
NSLog(#"%#",[array componentsJoinedByString:#","]);
I'm trying to send emails to a list that I get from a server which is an array of emails whose output is in this format
(
"john#gmail.com\n",
"katebell#gmail.com\n"
"\nakhil#gmail.com",
"mary#gmail.com",
"timcorb\n#gmail.com
)
Now as you can see some emails have newline characters in between and those emails doesnt get sent. I'm trying to find an efficient way to filter out those newlines, my current approach is to loop through all emails and check for newline in each email and if newline exist replace it with a null string. Is there a better way to do this or should I just stick with that? Also Will my current approach cause any issues in any other scenarios?
One way you can try using NSRegularExpression like this below :-
NSArray *array=#[#"john#gmail.com\n",#"katebell#gmail.com\n",#"\nakhil#gmail.com",#"mary#gmail.com",#"timcorb\n#gmail.com"];
NSString *string =[array componentsJoinedByString: #","];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
NSLog(#"%#",modifiedString);
Output:-
john#gmail.com,katebell#gmail.com,akhil#gmail.com,mary#gmail.com,timcorb#gmail.com
try something like this
NSString *fileName = #"\ntest\n";
fileName = [fileName stringByReplacingOccurrencesOfString:#"\n" withString:#""];
eg.
NSString * str = #"timcorb\n#gmail.com";
str = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"%#",str);
it will Log 2014-01-10 01:01:00.256 demo[26220] timcorb#gmail.com
You can use the below code for replacing characters in a string.
NSString *email = #"\nakhi\nl#gmail.com";
NSString *actualEmail = [email stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSMutableArray* emailArray = [[NSMutableArray alloc] init];
for (int _index = 0; _index < [yourArray count]; _index++) {
[emailArray addobject:[[yourArray objectAtIndex:_index] stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
}
This will give you your email array
I am new to ios development.
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:#"1," withString:#""];
My problem is i do not know how to check for any number i.e. stringByReplacingOccurrencesOfString:#"anyInt," where any Int is any integer number from 1 to N.
Thanks in advance!
Using regular expressions is the best solution:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[1-9]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
Check official NSRegularExpression documentation, there is also a good tutorial here
A regular expression is probably the easiest solution. Whether you want to remove just single digits or multiple digits, a regular expression can help.
NSString *aString = #"Apple 10, Banana 3, Carrot 5, Durian 42, Eggplant 4,";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[0-9]+," options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:aString options:0 range:NSMakeRange(0, [aString length]) withTemplate:#""];
NSLog(#"%#", newString);
// result should be "Apple Banana Carrot Durian Eggplant "
Regular expressions may seem overwhelming or difficult to understand at first, but it is only because they can be very powerful for searching and replacing text. Have a look at the overview section of the NSRegularExpression documentation for more information.
For nos in first part greater than 0, second part is shown. For 0 in first part, -- is shown.
Try the below code,
NSString * aString = #"1,10";
NSString *newString2;
NSArray *items = [aString componentsSeparatedByString:#","];
if([[items objectAtIndex:0] integerValue]>0)
newString2 = [items objectAtIndex:1];
else
newString2 = #"--";
Just these two lines to remove all numbers from a string.
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet: numbers] componentsJoinedByString:#""];
If you want to check the range and then you want to replace then use below api:-
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
why you want to check the existence of the Integer because ultimate you'll replace it with ''. So just use the below line
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:[NSString StringWithFormat:#"%d", anyInt], withString:#""];
Above line will fulfill your requirement.