I'd like to replace angle brackets and spaces in a string. For example #"< something >" goes to #"something". I'm currently trying:
NSString *s1 = #"< something >";
NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:#"[<> ]"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, s1.length)];
However I'm brand new to regular expressions and #"[<> ]" doesn't seem to work. What's the correct regular expression to use to remove angle brackets and spaces?
Note the documentation for NSRegularExpressionSearch:
You can use this option only with the rangeOfString:... methods.
So even if you had the right regex, you wouldn't be able to use it with this method.
For the situation you describe, it'll probably be easier to use -stringByTrimmingCharactersInSet: with a character set that includes '<' and ' '.
Update: Joshua Weinberg points out that you'd like to remove all occurrences of the characters '<', '>', and ' '. If that's the case, you'll want to look to NSRegularExpression's -stringByReplacingMatchesInString:options:range:withTemplate: method:
NSError *error = nil;
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:#"<> " options:0 error:&error];
NSString *s1 = #"< something >";
NSRange range = NSMakeRange(0, s1.length);
NSString *s2 = [re stringByReplacingMatchesInString:s1 options:0 range:range withTemplate:#""];
(I haven't tested that, but it should point you in the right direction.)
Here is a solution that strips out the characters: '<','>',' '
NSCharacterSet*mySet = [NSCharacterSet characterSetWithCharactersInString:#"<> "];
NSString *s1 = #"< something >";
NSArray * components = [s1 componentsSeparatedByCharactersInSet:
mySet];
NSMutableString * formattedS1 = [NSMutableString string];
for (NSString * s in components) {
[formattedS1 appendString:s];
}
NSLog(#"formatted string %#", formattedS1);
You can add whatever characters you need in the future to the first line
Related
I have a TextField which has values as shown below.
#"Testing<Car>Testing<Car2>Working<Car3 /Car 4> on the code"
Here I have to loop through the text field and check for the text present within Angle brackets(< >).
There can be space or any special characters within the Angle Brackets.
I tried using NSPredicate and also componentsSeparatedByString, but I was not able to get the exact text within.
Is there any way to get the exact text along with Angle Brackets. Like in the above mentioned example want only
#"<Car>,<Car2> , <Car3 /Car 4>"
Thanks for the help in Advance.
A possible solution is Regular Expression. The pattern checks for < followed by one or more non-> characters and one >.
enumerateMatchesInString extracts the substrings and append them to an array. Finally the array is flattened to a single string.
NSString *string = #"Testing<Car>Testing<Car2>Working<Car3 /Car 4> on the code";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:#"<[^>]+>" options:0 error:nil];
__block NSMutableArray<NSString *> *matches = [NSMutableArray array];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
if (result) [matches addObject:[string substringWithRange:result.range]];
}];
NSLog(#"%#", [matches componentsJoinedByString:#", "]);
We can solve it in different ways. Now I am showing one of the way. You can place textFiled.text in place of str.
NSString *str = #"This is just Added < For testing %# ___ & >";
NSRange r1 = [str rangeOfString:#"<" options: NSBackwardsSearch];
NSRange r2 = [str rangeOfString:#">" options: NSBackwardsSearch];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *sub = [str substringWithRange:rSub];
Given an NSString containing a sentence I would like to determine the number of gaps between the words.
I could use something like [[theString componentsSeparatedByString:#" "].
But that would only work if each gap is a single space character, there could be multiple.
You can use NSRegularExpression, like:
NSString *test = #"The quick brown fox jumped over the lazy dog";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\s+" options:0 error:NULL];
NSUInteger num = [regex numberOfMatchesInString:test options:0 range:NSMakeRange(0, test.length)];
NSLog(#"num: %lu", num);
The regular expression "\s+" matches one or more whitespace characters (it's written here with an extra "\" because we need a literal backslash in the NSString). numberOfMatchesInString:options:range: counts each run of one or more whitespace characters as a match, which is exactly what you want.
You can do it via componentsSeparatedByString - if you filter afterwards to ignore the empty strings:
NSString *theString = #"HI this is a test";
NSArray *arr = [theString componentsSeparatedByString:#" "];
arr = [arr filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *b) {
return [(NSString*)evaluatedObject length] > 0;
}]];
NSLog(#"number of words: %lu", arr.count);
NSLog(#"number of gaps: %lu", arr.count - 1);
Regex is the 'coolest' way, but this might be the fastest and cleanest
NSArray *components= [theString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"gaps: %f", components.count - 1);
I have a String W
NSString * stringTitle = link.title;
where i am getting link.title as #"I_AM_GOOD";
I need to remove the special characters "_" and make is as "I am Good".How to do that?
You haven't defined what you mean by a special character, and you seem to want to replace it with a space, not remove it.
NSArray * comps = [stringTitle componentsSeparatedByString:#"_"]
NSString * result = nil;
for(NSString *s in comps)
{
if(result)
{
result = [result stringByAppendingFormat:#" %#",[s capitalizedString];
}
else
{
result = [s capitalizedString];
}
}
If you have other special characters that you want to replace, then use
-componentsSeparatedByCharactersInSet:
Easiest way to replace any characeter from a string is as below. Make sure that you use a NSMutableString.
[stringTitle replaceOccurrencesOfString:#"_" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[stringTitle length])];
The most easiest way to do it
strTest = [strTest stringByReplacingOccurrencesOfString:#"_" withString:#" "];
I have a NSString category I am working on to perform character substitution similar to PHP's strtr. This method takes a string and replaces every occurrence of each character in fromString and replaces it with the character in toString with the same index. I have a working method but it is not very performant and would like to make it quicker and able to handle megabytes of data.
Edit (for clarity):
stringByReplacingOccurrencesOfString:withString:options:range: will not work. I have to take a string like "ABC" and after replacing "A" with "B" and "B" with "A" end up with "BAC". Successive invocations of stringByReplacingOccurrencesOfString:withString:options:range: would make a string like "AAC" which would be incorrect.
Suggestions would be great, sample code would be even better!
Code:
- (NSString *)stringBySubstitutingCharactersFromString:(NSString *)fromString
toString:(NSString *)toString;
{
NSMutableString *substitutedString = [self mutableCopy];
NSString *aCharacterString;
NSUInteger characterIndex
, stringLength = substitutedString.length;
for (NSUInteger i = 0; i < stringLength; ++i) {
aCharacterString = [NSString stringWithFormat: #"%C", [substitutedString characterAtIndex:i]];
characterIndex = [fromString rangeOfString:aCharacterString].location;
if (characterIndex == NSNotFound) continue;
[substitutedString replaceCharactersInRange:NSMakeRange(i, 1)
withString:[NSString stringWithFormat:#"%C", [toString characterAtIndex:characterIndex]]];
}
return substitutedString;
}
Also this code is executed after every change to text in a text view. It is passed the entire string every time. I know that there is a better way to do it, but I do not know how. Any suggestions for this would be most certainly appreciated!
You can make that kind of string substitution with NSRegularExpression either modifying an mutable string or creating a new immutable string. It will work with any two strings to substitute (even if they are more than one symbol) but you will need to escape any character that means something in a regular expression (like \ [ ( . * ? + etc).
The pattern finds either of the two substrings with the optional "anything" between and than replaces them with the two substrings with each other preserving the optional string between them.
// These string can be of any length
NSString *firstString = #"Axa";
NSString *secondString = #"By";
// Escaping of characters used in regular expressions has NOT been done here
NSString *pattern = [NSString stringWithFormat:#"(%#|%#)(.*?)(%#|%#)", firstString, secondString, firstString, secondString];
NSString *string = #"AxaByCAxaCBy";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
// Insert error handling here...
}
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"$3$2$1"];
NSLog(#"Before:\t%#", string); // AxaByCAxaCBy
NSLog(#"After: \t%#", modifiedString); // ByAxaCByCAxa
As the title said, I need to format a string of text in format like: "HELLO, WORLD. HOW ARE YOU?" into "Hello, world. How are you?", is there any standard method for doing this in iOS? Or is there any sample code ?
Thanks!
I don't know standard method to do this, and I don't think there is one.
But the NSString provides methods such : -(NSString *)capitalizedString; which returns a new string, with the first character of each word in upper case. After breaking correctly your string you could use it. Also think of getting a string in lower case using : -(NSString *)lowercaseString.
There is no direct way to capitalize the first characters of sentences in a paragraph. NSString just has a method capitalizedString which capitalizes each and every word. You have to create your own logic to achieve this. You can try the following code.
- (NSString *)captilizeParagraph:(NSString *)paragraph {
if ([paragraph length] == 0) return paragraph;
NSArray *sentences = [paragraph componentsSeparatedByString:#". "];
NSMutableArray *capitalizedSentences = [NSMutableArray array];
for (NSString *sentence in sentences) {
sentence = [sentence lowercaseString];
sentence = [sentence stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[sentence substringToIndex:1] uppercaseString]];
[capitalizedSentences addObject:sentence];
}
NSString *capitalizedParagrah = [capitalizedSentences componentsJoinedByString:#". "];
return capitalizedParagrah;
}
Note: The above code assumes that all the sentences in the paragraph ends with characters ". " (a dot and a space) except the last sentence(it can end with any character). If a sentence ends with some other characters like "? " or "! ", then this method will return a not-fully-formatted string.
-(NSString *)normalizeString{
__block NSString *string = [self lowercaseString];
string = [string stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[string substringToIndex:1] uppercaseString]];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[\\p{P}-[,]]" options:0 error:nil];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
if(result.range.location + 2 < string.length) string = [string stringByReplacingCharactersInRange:NSMakeRange(result.range.location + 2, 1) withString:[[self substringWithRange:NSMakeRange(result.range.location + 2, 1)] uppercaseString]];
}];
return string;
}
Assuming that 2 characters after the punctuation is the first character of the next sentence, this works.