Replace each word in a string with (the first letter + number of characters between + last letter) - objective-c

I'm using objective-c to parse a sentence here:
NSString *myString = #“Some words to form a string”;
Here is what I have so far:
NSMutableString *firstCharacters = [NSMutableString string];
NSMutableString *lastCharacters = [myString substringFromIndex:[myString length] - 1]
NSArray *arrayOfWords = [myString componentsSeparatedByString:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords) {
if ([word length] > 0) {
NSString *firstLetter = [word substringToIndex:1];
[firstCharacters appendString:lastCharacters];
and then I am really stumped at this point. I want to NSLog the recombined string so that it looks like this:
"S2e w3s to f2m a s3g"

Please try following code :
NSString *myString = #"Some words to form a string";
NSArray *wordsInSentence = [myString componentsSeparatedByString:#" "];
NSMutableArray *expectedResultArray = [[NSMutableArray alloc] init];
for (NSString *word in wordsInSentence) {
NSString *finalExpectedString = word;
if (word.length > 2) {
NSString *firstLetterInWord = [word substringToIndex:1];
NSString *lastLetterInWord = [word substringFromIndex:[word length] - 1];
finalExpectedString = [NSString stringWithFormat:#"%#%d%#", firstLetterInWord, (int)word.length - 2, lastLetterInWord];
}
[expectedResultArray addObject:finalExpectedString];
}
NSString *printString = [expectedResultArray componentsJoinedByString:#" "];
NSLog(#"Result : %#", printString);

Related

Objective C - Multi line string using stringByAppendingFormat

I'm having an issue with the following code. I want the resultant multiLineTitle to look like this
Each
Word
Should
Have
Its
Own
Line
But when I run this program, multiLineTitle ends up null. Can anyone spot the issue?
NSString *title = "Each Word Should Have Its Own Line";
NSString *multiLineTitle;
NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
for (int len = 0; len < [words count]; len++){
multiLineTitle = [multiLineTitle stringByAppendingFormat:#"%# \n", words[len]];
}
assign empty string to multiLineTitle or allocate memory for multiLineTitle.
NSString *multiLineTitle = #"";
or
NSString *multiLineTitle = [[NSString alloc]init];
solution....
NSString *title =#"Each Word Should Have Its Own Line";
NSMutableString *multiLineTitle =[[NSMutableString alloc] init];
NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
for (int len = 0; len < [words count]; len++){
[multiLineTitle appendFormat:#"%#\n",[words objectAtIndex:len]];
}
NSLog(#"multiLineTitle:%#",multiLineTitle);
ans:
multiLineTitle:Each
Word
Should
Have
Its
Own
Line

Substring to nth character

I need to substring to the 2nd comma in an NSString.
Input:
NSString *input = #"title, price, Camry, $19798, active";
Desired Output:
NSString *output = #"title, price";
Thanks!
UPDATE:
I have the following but the problem is it needs to skip the last comma:
NSString *output = [input rangeOfString:#"," options:NSBackwardsSearch];
Try this:
- (NSString *)substringOfString:(NSString *)base untilNthOccurrence:(NSInteger)n ofString:(NSString *)delim
{
NSScanner *scanner = [NSScanner scannerWithString:base];
NSInteger i;
for (i = 0; i < n; i++)
{
[scanner scanUpToString:delim intoString:NULL];
[scanner scanString:delim intoString:NULL];
}
return [base substringToIndex:scanner.scanLocation - delim.length];
}
this code should do what you need:
NSString *input = #"title, price, Camry, $19798, active";
NSArray *array = [input componentsSeparatedByString:#","];
NSArray *subArray = [array subarrayWithRange:NSMakeRange(0, 2)];
NSString *output = [subArray componentsJoinedByString:#","];
NSLog(output);
You could split -> splice -> join that string like this in objc:
NSString *input = #"title, price, Camry, $19798, active";
// split by ", "
NSArray *elements = [input componentsSeparatedByString: #", "];
// grab the subarray
NSArray *subelements = [elements subarrayWithRange: NSMakeRange(0, 2)];
// concat by ", " again
NSString *output = [subelements componentsJoinedByString:#", "];
You can try something like this:
NSArray *items = [list componentsSeparatedByString:#", "];
NSString result = #"";
result = [result stringByAppendingString:[items objectAtIndex:0]];
result = [result stringByAppendingString:#", "];
result = [result stringByAppendingString:[items objectAtIndex:1]];
You have to check you have at least two items if you want avoid an exception.
There's really nothing wrong with simply writing the code to do what you want. Eg:
int commaCount = 0;
int i;
for (i = 0; i < input.count; i++) {
if ([input characterAtIndex:i] == (unichar) ',') {
commaCount++;
if (commaCount == 2) break;
}
}
NSString output = nil;
if (commaCount == 2) {
output = [input substringToIndex:i];
}
You could create an NSString category to handle finding nth occurrences of any string. This is example is for ARC.
//NSString+MyExtension.h
#interface NSString(MyExtension)
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string;
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
options:(NSStringCompareOptions)options;
#end
#implementation NSString(MyExtension)
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
{
return [self substringToNthOccurrence:nth ofString:string options:0];
}
-(NSString*)substringToNthOccurrence:(NSUInteger)nth
ofString:(NSString*)string
options:(NSStringCompareOptions)options
{
NSUInteger location = 0,
strlength = [string length],
mylength = [self length];
NSRange range = NSMakeRange(location, mylength);
while(nth--)
{
location = [self rangeOfString:string
options:options
range:range].location;
if(location == NSNotFound || (location + strlength) > mylength)
{
return [self copy]; //nth occurrence not found
}
if(nth == 0) strlength = 0; //This prevents the last occurence from being included
range = NSMakeRange(location + strlength, mylength - strlength - location);
}
return [self substringToIndex:location];
}
#end
//main.m
#import "NSString+MyExtension.h"
int main(int argc, char *argv[])
{
#autoreleasepool {
NSString *output = [#"title, price, Camry, $19798, active" substringToNthOccurrence:2 ofString:#","];
NSLog(#"%#", output);
}
}
*I'll leave it as an exercise for someone to implement the mutable versions.

stringwithformat issue in string searching

I did following experiment. Can any one point out why strings initialized with stringwithformat fail in string searching?
NSString *test1 = #"Hello";
NSString *test2 = #"Hello";
NSString *test3 = [NSString stringWithFormat:#"%# ", test2];
NSRange titleResultsRange = [test1 rangeOfString:test2 options:NSCaseInsensitiveSearch];
I get titleResultsRange.length > 0
But when I do -
NSRange titleResultsRange = [test1 rangeOfString:test3 options:NSCaseInsensitiveSearch];
I get titleResultsRange.length = 0
Why?
Could it be that test3 is "Hello " not "Hello".
NSString *test1 = #"Hello";
NSString *test2 = #"Hello";
NSString *test3 = [NSString stringWithFormat:#"%#", test2];
NSRange titleResultsRange = [test1 rangeOfString:test2 options:NSCaseInsensitiveSearch];
Try now. In your code test3 string contain extra white space.

How to get values after "\n" character?

I want to take all values after a new line character \n from my string. How can I get those values?
Try this:
NSString *substring = nil;
NSRange newlineRange = [yourString rangeOfString:#"\n"];
if(newlineRange.location != NSNotFound) {
substring = [yourString substringFromIndex:newlineRange.location];
}
Take a look at method componentsSeparatedByString here.
A quick example taken from reference:
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
this will produce a NSArray with strings separated: { #"Norman", #"Stanley", #"Fletcher" }
Here is similar function which splits the string by delimeter and return array with two trimmed values.
NSArray* splitStrByDelimAndTrim(NSString *string, NSString *delim)
{
NSRange range = [string rangeOfString: delim];
NSString *first;
NSString *second;
if(range.location == NSNotFound)
{
first = #"";
second = string;
}
else
{
first = [string substringToIndex: range.location];
first = [first stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
second = [string substringFromIndex: range.location + 1];
second = [second stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
return [NSArray arrayWithObjects: first, second, nil];
}

make array out of string with variable number of spaces in Objective-C

This is the code that I would use if it was always single spaces in between words. Since I have multiple spaces in between some words how can my code be changed to remove the extra spaces when using componentsSeparatedBySring. I'm new to OBjective-C so any help would be greatly appreciated!
Here is my code:
NSString *myString = #"One Two Three Four Five";
NSArray *myArray = [myString componentsSeparatedByString: #" "];
Use NSScanner instead:
NSMutableArray *results = [NSMutableArray array];
NSScanner *scanner = [NSScanner scannerWithString:input];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#" "];
while ([scanner isAtEnd] == NO)
{
NSString *string;
[scanner scanUpToCharactersFromSet:charSet intoString:&string];
[results addObject:string];
}
+ (NSArray *)componentsInString:(NSString *)string withSeparacterInString:(NSString *)separaterStr
{
if (!string || !separaterStr || [separaterStr length] < 1)
return [NSArray array];
NSMutableArray *arr = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:separaterStr]] mutableCopy];
[arr removeObject:#""]; // removes all empty components
return arr;
}
NSArray *arr = [Utils componentsInString:#"12 123 \n 14 " withSeparacterInString:#" \n"];