How to add a character at start and end of every word in NSString - ios

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 :)

Related

Regex for a string combination

NSString *fmtpAudio = #"a=fmtp:111 ";
NSString *stereoString = #";stereo=1;sprop-stereo=1";
NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio];
if (componentArray.count >= 2) {
NSString *component = [componentArray objectAtIndex: 1];
NSArray *fmtpArray = [component componentsSeparatedByString:#"\r\n"];
if (fmtpArray.count > 1) {
NSString *fmtp = [fmtpArray firstObject];
NSString *fmtpAudioOld = [NSString stringWithFormat:#"%#%#", fmtpAudio, fmtp];
fmtpAudio = [NSString stringWithFormat:#"%#%#%#", fmtpAudio, fmtp, stereoString];
NSString *stereoEnabledSDP = [NSString stringWithString: localSdpMutableStr];
stereoEnabledSDP = [stereoEnabledSDP stringByReplacingOccurrencesOfString: fmtpAudioOld withString: fmtpAudio];
localSdpMutableStr.string = stereoEnabledSDP;
}
}
Consider below example String:
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
In the above example string, a=fmtp:111 can appear anywhere in the string.
We have to get the string between a=fmtp:111 and the next first appearance of \r\n which is av=1 in our case
Now we have to append ;stereo=1;sprop-stereo=1 to av=1 and append back to the original string.
The final output should be
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1;stereo=1;sprop-stereo=1\r\n
a=fmtp:92 av=2\r\n
Is it possible to achieve the above chunk of logic with Replace with Regex pattern?
You can use
NSError *error = nil;
NSString *fmtpAudio = #"^a=fmtp:111 .*";
NSString *stereoString = #"$0;stereo=1;sprop-stereo=1";
NSString *myText = #"a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:fmtpAudio options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate: stereoString];
NSLog(#"%#", modifiedString);
Output:
a=fmtp:93 av=2
a=fmtp:111 av=1;stereo=1;sprop-stereo=1
a=fmtp:92 av=2
See the regex demo.
Details
^ - start of a line (^ starts matching line start positions due to the options:NSRegularExpressionAnchorsMatchLines option)
a=fmtp:111 - a literal string
.* - any zero or more chars other than line break chars as many as possible.
The $0 in the replacement pattern is the backreference to the whole match value.

I want to remove static text from string - iOS

Hi I have a News Reader and I keep getting a string like this -
two New York police officers shot dead in 'ambush'
I want the string two New York police officers shot dead in ambush
How can I scan from & to ; and then delete occurrences of the scan.
I created a scanner like so -
NSString *webString222222 = filteredTitle2;
NSScanner *stringScanner222222 = [NSScanner scannerWithString:webString222222];
NSString *content222222 = [[NSString alloc] init];
[stringScanner222222 scanUpToString:#"&" intoString:Nil];
[stringScanner222222 scanUpToString:#";" intoString:&content222222];
NSString *filteredTitle222 = [content222222 stringByReplacingOccurrencesOfString:content222222 withString:#""];
NSString *filteredTitle22 = [filteredTitle222 stringByReplacingOccurrencesOfString:#"&" withString:#""];
But when I do this code the whole text disappears! Every single word.
When I check the title in my NSLog that is the only & sign in there and the only ; sign in there!
Im not sure where I went wrong here.
If the special characters you are encountering are all relatively consistent you can merely replace each of those substrings with the empty string, like so:
NSString *cleansedString = [filteredTitle2 stringByReplacingOccurrencesOfString:#"'"
withString:#""];
You can use NSRegularExpression to build proper matching pattern:
NSString *pattern = #"\\&#[0-9]+;";
NSString *str = #"two New York police officers shot dead in 'ambush'";
NSLog(#"Original test: %#",str);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:&error];
if (error != nil)
{
NSLog(#"ERror: %#",error);
}
else
{
NSString *replaced = [regex stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""];
NSLog(#"Replaced test: %#",replaced);
}
See https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html

Filter new line from array of email strings

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

add whitespace to string

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);

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources