Is there an easy way to transform a string "dino mcCool" to a string "Dino McCool"?
using the 'capitalizedString' method I would just get #"Dino Mccool"
You can enumerate the words of the string and modify each word separately.
This works even if the words are separated by other characters than a space character:
NSString *str = #"dino mcCool. foo-bAR";
NSMutableString *result = [str mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[result replaceCharactersInRange:NSMakeRange(substringRange.location, 1)
withString:[[substring substringToIndex:1] uppercaseString]];
}];
NSLog(#"%#", result);
// Output: Dino McCool. Foo-BAR
Try this
- (NSString *)capitilizeEachWord:(NSString *)sentence {
NSArray *words = [sentence componentsSeparatedByString:#" "];
NSMutableArray *newWords = [NSMutableArray array];
for (NSString *word in words) {
if (word.length > 0) {
NSString *capitilizedWord = [[[word substringToIndex:1] uppercaseString] stringByAppendingString:[word substringFromIndex:1]];
[newWords addObject:capitilizedWord];
}
}
return [newWords componentsJoinedByString:#" "];
}
Related
I have an string value.
NSString *getAllData = #"0,testing,u,4,u";
Now I want to increment in all the numeric values in the string e.g. #"1,testing,u,5,u"
How can this be done?
Here is your answer...
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *getAllData = #"0,testing,u,4,u";
NSMutableArray *resultArray = [NSMutableArray array];
[[getAllData componentsSeparatedByString:#","] enumerateObjectsUsingBlock:^(NSString *subString, NSUInteger idx, BOOL *stop) {
if([self isNumeric:subString])
{
[resultArray addObject:[NSString stringWithFormat:#"%d", [subString intValue] + 1]];
}
else [resultArray addObject:subString];
}];
NSString *finalOutput = [resultArray componentsJoinedByString:#","];
NSLog(#"%#", finalOutput);
}
- (BOOL)isNumeric:(NSString *)aString
{
NSString *expression = [NSString stringWithFormat:#"^[0-9]*$"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString options:0 range:NSMakeRange(0, [aString length])];
return (numberOfMatches != 0);
}
You can use the NSScanner class to find the numbers in the string, and convert them to integers. The NSMutableString class can be used to accumulate the output string.
- (NSString *)incrementValuesInString:(NSString *)input
{
NSScanner *scanner = [NSScanner scannerWithString:input];
[scanner setCharactersToBeSkipped:nil];
NSMutableString *result = [NSMutableString string];
while ( ![scanner isAtEnd] )
{
// copy characters to the result string until a digit is found
NSString *temp;
if ( [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&temp] )
[result appendString:temp];
// scan the number and increment it
if ( ![scanner isAtEnd] )
{
int value;
if ( [scanner scanInt:&value] )
[result appendFormat:#"%d", value + 1];
}
}
return( [result copy] );
}
I have the following code which works:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[a-cA-C2][m-oM-O][a-cA-C2]" options:0 error:NULL];
NSString *str = #"Ana";
NSTextCheckingResult *match1 = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
NSLog(#"check is exist: %#", [str substringWithRange:[match1 rangeAtIndex:0]]);
Here are my questions:
1.Is there a way I can change the NSString with an NSMutableArray and save the NSTextCheckingResult in a NSMutableArray called filterArray?
2.How to highlight the matching values when displaying then in a TextField?
If I correctly understand your question,
you want to use NSArray of strings, and receive NSArray of matching results for each string.
So, 1:
NSArray *arrayOfStrings = /* Your array */;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[a-cA-C2][m-oM-O][a-cA-C2]" options:0 error:NULL];
NSMutableArray *filterArray = [NSMutableArray array];
[arrayOfStrings enumerateObjectsUsingBlock:^(NSString * str, NSUInteger idx, BOOL * stop) {
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
if (match) {
[filterArray addObject:match];
}
else {
[filterArray addObject:[NSNull null]];
}
NSLog(#"String #%i. check is exist: %#",idx, [str substringWithRange:[match rangeAtIndex:0]]);
}];
2: For highlighting ranges of the string you need to use NSAttributedString. Please, see this question for the answer how:) How do you use NSAttributedString?
After you formed attributed string, set it to textfield:
NSAttributedString * attributedString;
UITextField *textField;
[ttextField setAttributedText:attributedString];
i like to know how to fetch the specific string which starts with &abc and ends with &. I tried with had prefix and sufix . but this is not new line ,
&xyz;123:183:184:142&
&abc;134:534:435:432&
&qwe;323:535:234:532&
my code :
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:#"&abc" intoString:nil]; //
NSString *substring = nil;
[scanner scanString:#"&abc" intoString:nil]; // Scan the # character
if([scanner scanUpToString:#"&" intoString:&substring]) {
// If the space immediately followed the &, this will be skipped
[substrings addObject:substring];
NSLog(#"substring is :%#",substring);
}
// do something with substrings
[substrings release];
how to make "scanner scanUpToString:#"&abc" and count ":"==3 till "#"???? can help me
NSArray *arr = [NSArray arrayWithObjects:#"&xyz;123:183:184:142&",
#"&abc;134:534:435:432&",
#"&qwe;323:535:234:532&",
#"& I am not in it",
#"&abc I am out &" ,nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self BEGINSWITH[cd] %# AND self ENDSWITH[cd] %#",#"&abc",#"&"];
NSLog(#"Sorted Array %#",[arr filteredArrayUsingPredicate:predicate]);
NSArray *sortedArray = [arr filteredArrayUsingPredicate:predicate];
NSMutableArray *finalResult = [NSMutableArray arrayWithCapacity:0];
for(NSString *string in sortedArray)
{
NSString *content = string;
NSRange range1 = [content rangeOfString:#"&abc"];
if(range1.length > 0)
content = [content stringByReplacingCharactersInRange:range1 withString:#""];
NSRange range2 = [content rangeOfString:#"&"];
if(range2.length > 0)
content = [content stringByReplacingCharactersInRange:range2 withString:#""];
[finalResult addObject:content];
}
NSLog(#"%#",finalResult);
Try using NSRegularExpression:
- (BOOL)isValidString:(NSString *)string
{
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:#"^&abc.*&$" options:0 error:NULL];
NSTextCheckingResult *result = [regularExpression firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
return (result != nil);
}
I have a method in Objective-c that takes in an NSDictionary and returns the values as a space-separated NSString. This application is cross-platform, and as such I cannot use fast enumeration. This is what I have so far, followed by the output (which shows that the String is never created):
-(NSString *)stringValuesFromDict:(NSDictionary *map)
{
NSArray *values = [map allValues];
NSString *params = [NSString string];
NSLog(#"values length: %d", [values count]);
NSLog(#"values = %#", [values description]);
for (int i = 0; i < [values count]; i++)
{
[params stringByAppendingString:[values objectAtIndex:i]];
[params stringByAppendingString:#" "];
}
NSLog(#"params = %#", params);
return params;
}
The NSDictionary:
{"arg1"="monkey"}
The output:
values length: 1
values = (
monkey
)
params =
What am I doing wrong? How can I get params to be set to monkey?
If I read the question correctly, all you need is
[[dict allValues] componentsJoinedByString:#" "]
You need a mutable string. Change this:
NSString *params = [NSString string];
to this:
NSMutableString *params = [NSMutableString string];
Then change these:
[params stringByAppendingString:[values objectAtIndex:i]];
[params stringByAppendingString:#" "];
to these:
[params appendString:[values objectAtIndex:i]];
[params appendString:#" "];
stringByAppendingString: returns a new string. So you would have to do something like this:
params = [params stringByAppendingString:[values objectAtIndex:i]];
But the disadvantage is, that every time a new string is created, which is wasting memory
You should propably use a NSMutableString instead. And then you can just call
[params appendString:[values objectAtIndex:i]];
Here is the example:
<aNodeName thsisjijdsnjdnjsd>, and I would like to remove thsisjijdsnjdnjsd,
How can I detect the string which is before the > and after the space , and trim out it in objective C? Also, please remind that I don't know the aNodeName or thsisjijdsnjdnjsd, because the data may turn out something like this:
<anotherNodeName zxzxxzxzxz>, and I need to remove zxzxxzxzxz.
Basically you have two options
Regular expressions
NSString *string = #"<aNodee thsisjijdsnjdnjsd>";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"<(\\S+)( .*)>" options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
[matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *result, NSUInteger idx, BOOL *stop) {
NSString* nodeName = [string substringWithRange:[result rangeAtIndex:1]];
NSString* value = [string substringWithRange:[result rangeAtIndex:2]];
NSLog(#"%# %#",nodeName, value);
}];
Note, that you shouldn't parse complex html with Regular Expressions.
NSScanner
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL recordingValue = NO;
NSMutableString *valueString = [#"" mutableCopy];
[scanner setScanLocation:0];
while (![scanner isAtEnd]) {
NSString *charAtlocation = [string substringWithRange:NSMakeRange([scanner scanLocation], 1)];
if ([charAtlocation isEqualToString:#" "]){
recordingValue = YES;
[valueString appendString:#" "];
} else{
if ([charAtlocation isEqualToString:#">"]){
recordingValue = NO;
} else if (recordingValue) {
[valueString appendString:charAtlocation];
}
}
[scanner setScanLocation:[scanner scanLocation]+1];
} ;
NSLog(#"Scanner approach: %#", valueString);
NSLog(#"Scanner approach: %#", [string stringByReplacingOccurrencesOfString:valueString withString:#""]);
Complete command line based example
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSString *string = #"<aNodee thsisjijdsnjdnjsd> ";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"<([a-zA-z]+)( .*)>" options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
[matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *result, NSUInteger idx, BOOL *stop) {
NSString* nodeName = [string substringWithRange:[result rangeAtIndex:1]];
NSString* value = [string substringWithRange:[result rangeAtIndex:2]];
NSLog(#"Regex approach: %# %#",nodeName, value);
NSLog(#"Regex approach: %#", [string stringByReplacingOccurrencesOfString:value withString:#""]);
}];
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL recordingValue = NO;
NSMutableString *valueString = [#"" mutableCopy];
[scanner setScanLocation:0];
while (![scanner isAtEnd]) {
NSString *charAtlocation = [string substringWithRange:NSMakeRange([scanner scanLocation], 1)];
if ([charAtlocation isEqualToString:#" "]){
recordingValue = YES;
[valueString appendString:#" "];
} else{
if ([charAtlocation isEqualToString:#">"]){
recordingValue = NO;
} else if (recordingValue) {
[valueString appendString:charAtlocation];
}
}
[scanner setScanLocation:[scanner scanLocation]+1];
} ;
NSLog(#"Scanner approach: %#", valueString);
NSLog(#"Scanner approach: %#", [string stringByReplacingOccurrencesOfString:valueString withString:#""]);
}
return 0;
}
Output:
Regex approach: aNodee thsisjijdsnjdnjsd
Regex approach: <aNodee>
Scanner approach: thsisjijdsnjdnjsd
Scanner approach: <aNodee>