How to print the reverse of NSString in objective c without using componentsSeparatedByString method? - objective-c

I want to make a method which gives reverse of string.suppose I pass a NSString "Welcome to Objective C" in method and that method return a reverse of string like "C Objective to Welcome" not "C evitcejbO ot emocleW" without the use of componentsSeparatedByString method.
Is it possible to do with Objective c..?
Please help.

You can enumerate strings by words.
NSString *string = #"Welcome to Objective-C!";
NSMutableArray *words = [NSMutableArray array];
[string enumerateLinguisticTagsInRange:NSMakeRange(0, [string length])
scheme:NSLinguisticTagSchemeTokenType
options:0
orthography:nil
usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
[array addObject:[string substringWithRange:tokenRange]];
}];
NSMutableString *reverseString = [[NSMutableString alloc] init];
for (NSString *word in [words reverseObjectEnumerator]){
[reverse appendString:word];
}
NSLog(#"%#", reverseString);
This will print...
"!C-Objective to Welcome"
You can change the options to omit whitespaces and stuff...

I used below method for reversing string in iOS
- (NSString *)reverseString:(NSString *)stringToReverse
{
NSMutableString *reversedString = [NSMutableString stringWithCapacity:[stringToReverse length]];
[stringToReverse enumerateSubstringsInRange:NSMakeRange(0, [stringToReverse length])
options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}

Sorry I misread your question earlier. I did it using a series of loops, my answer is messier than Fogmeister but I wanted to give it a shot to see if I could do it.
NSString *str = #"This is a test";
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i = 0; i < [str length]; i++)
{
char sTest = [str characterAtIndex:i];
if(sTest == ' ')
{
[array addObject:[NSNumber numberWithInt:i]];
}
}
NSInteger iNext = [[array objectAtIndex:[array count]-1] integerValue];
iNext+=1;
if(iNext < [str length])
{
[array addObject:[NSNumber numberWithInt:iNext]];
}
NSMutableArray *wordArray = [[NSMutableArray alloc] init];
for(int i = 0; i < [array count]; i++)
{
if (i == 0)
{
int num = [[array objectAtIndex:i] integerValue];
NSString *s = [[str substringFromIndex:0] substringToIndex:num];
[wordArray addObject:s];
}
else if(i == [array count]-1)
{
int prev = [[array objectAtIndex:i-1] integerValue]+1;
int num = [str length];
NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
[wordArray addObject:s];
}
else
{
int prev = [[array objectAtIndex:i-1] integerValue]+1;
int num = [[array objectAtIndex:i] integerValue];
NSString *s = [[str substringToIndex:num] substringFromIndex:prev];
[wordArray addObject:s];
}
}
NSMutableArray *reverseArray = [[NSMutableArray alloc]init];
for(int i = [wordArray count]-1; i >= 0; i--)
{
[reverseArray addObject:[wordArray objectAtIndex:i]];
}
NSLog(#"%#", reverseArray);

Here i have done with replacing character with minimal number of looping. log(n/2).
NSString *string=#"Happy World";
NSInteger lenth=[string length];
NSInteger halfLength=[string length]/2;
for(int i=0;i<halfLength;i++)
{
NSString *leftString=[NSString stringWithFormat:#"%c",[string characterAtIndex:i]];
NSString *rightString=[NSString stringWithFormat:#"%c",[string characterAtIndex:(lenth-i-1)]];
string= [string stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:rightString];
string=[string stringByReplacingCharactersInRange:NSMakeRange((lenth-i-1), 1) withString:leftString];
}
NSLog(#"%#",string);

Try This , It's working perfect as per your expectation ,
Call Function :-
[self reversedString:#"iOS"];
Revers String Function :-
-(void)reversedString :(NSString *)reversStr
{ // reversStr is "iOS"
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [reversStr length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[reversStr substringWithRange:subStrRange]];
}
NSLog(#"%#", reversedString); // outputs "SOi"
}
Hope So this is help for some one .

There is no API to do that, if that's what you are asking.
You can always iterate through the string looking for white spaces (or punctuation, it depends on your needs), identify the words and recompose your "reversed" message manually.

Related

Formatting NSString, Objective-C

What would be the best way to transform NSStrings like these (mixed case)
#"Hello lorem ipsum";
#"i am a test";
to these (camel case without spaces)
#"helloLoremIpsum";
#"iAmATest";
Try this
Using For Loop
- (NSString *)camelCased:(NSString *)aString {
NSMutableString *result = [NSMutableString new];
NSArray *words = [aString componentsSeparatedByString: #" "];
for (NSUInteger i = 0; i < words.count; i++) {
if (i==0) {
[result appendString:([words[i] lowercaseString])];
}
else {
[result appendString:([words[i] capitalizedString])];
}
}
return result;
}
Using Block
- (NSString *)camelCasedUsingBlock:(NSString *)aString {
NSMutableArray *words = [[NSMutableArray alloc] init];
[[aString componentsSeparatedByString:#" "] enumerateObjectsUsingBlock:^(id anObject, NSUInteger idx, BOOL *stop) {
if (idx == 0) {
[words addObject:[anObject lowercaseString]];
}
else{
[words addObject:[anObject capitalizedString]];
}
}];
return [words componentsJoinedByString:#""];
}
NSLog(#"%#",[self camelCased:#"Hello lorem ipsum"]);//helloLoremIpsum
NSLog(#"%#",[self camelCased:#"i am a test"]);//iAmATest
It's overkill but TransformerKit has a bunch of NSValueTransformers that can be used, one is for camel casing. The relevant file is TTTStringTransformers.m if you want to build your own solution for lightness.

combine multiple array values into one string value?

I want to combine the array values into one string.
my arrays are like...
array1=[#"fizan",#"nike",#"pogo"];
array2=[#"round",#"rectangle",#"square"];
array3=[#"frame",#"frame",#"frame"];
I need like this...
value1 = fizan round frame
value2 = nike rectangle frame
value3 = pogo square frame
try this:
NSArray *array1= #[#"fizan",#"nike",#"pogo"];
NSArray *array2= #[#"round",#"rectangle",#"square"];
NSArray *array3= #[#"frame",#"frame",#"frame"];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:#[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;
for (int i = 0; i<array1.count; i++) {
a = #"";
for (int j = 0; j<count; j++) {
a = [a isEqualToString: #""] ? [NSString stringWithFormat:#"%#",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:#"%# %#",a,[[array objectAtIndex:j] objectAtIndex:i]];
}
[output addObject:a];
}
for (int i = 0; i < output.count; i++) {
NSLog(#"value %i -> %#",i+1,output[i]);
}
Hope this helps!
UPDATE:
NSArray *array1= #[#"fizan",#"",#"pogo"];
NSArray *array2= #[#"round",#"rectangle",#"square"];
NSArray *array3= #[#"frame",#"frame",#"frame"];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:#[array1,array2,array3]];
NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a;
NSInteger count = array.count;
for (int i = 0; i<array1.count; i++) {
a = #"";
for (int j = 0; j<count; j++) {
a = [a isEqualToString: #""] ? [NSString stringWithFormat:#"%#",[[array objectAtIndex:j] objectAtIndex:i]] : [NSString stringWithFormat:#"%# %#",a,[[array objectAtIndex:j] objectAtIndex:i]];
}
[output addObject:a];
}
for (int i = 0; i < output.count; i++) {
NSLog(#"value %i -> %#",i+1,output[i]);
}
I have tested this code. It works perfect. Check again and reconsider the issue.
Do this
NSArray *array1 = #[#"fizan", #"nike", #"pogo"];
NSString *value = [array1 componentsJoinedByString:#" "];
NSLog(#"value = %#", value);
Output will get like
value = fizan nike pogo
For your case
NSArray *completeArray = #[#[#"fizan",#"nike",#"pogo"], #[#"round",#"rectangle",#"square"], #[#"frame",#"frame",#"frame"]];
NSMutableArray *resultArray = [NSMutableArray array];
unsigned long count = 1;
for (int i = 0; i< count; i++) {
NSMutableArray *listArray = [NSMutableArray array];
for (NSArray *itemArray in completeArray) {
count = MAX(count,itemArray.count);
if (i < itemArray.count) {
[listArray addObject:itemArray[i]];
}
}
[resultArray addObject:listArray];
}
for (NSArray *itemArray in resultArray) {
NSString *value = [itemArray componentsJoinedByString:#" "];
NSLog(#"value = %#", value);
}
output
value = fizan round frame
value = nike rectangle frame
value = pogo square frame

Search an NSMutableArray with strings if string is equal to other string NLog position of item

I have an NSMutableArray with items in it.
I would like to compare every item with a string.
If the string is the same then the next item of the array should be stored in another array.
NSString *string2 = [NSString stringWithFormat:#"Period:"];
// Filtern nach Periode
NSMutableArray *Eventarray =[NSMutableArray array];
for(int i=0;i<[lines count]; i++)
{
NSMutableString *string1 = [NSMutableString stringWithFormat: #"%#",[[lines objectAtIndex:i]description]];
// NSLog(#"%#",string1);
int index = [[lines objectAtIndex:i] indexOfObject:#"Period:"];
NSLog(#"%#",index);
if ([[lines objectAtIndex:i] isEqualToString:#"Period:"])
{
//strings are same
NSLog(#"ii");
NSLog(#"ii");
int e=i+1;
NSMutableString *Periode = [NSMutableString stringWithFormat: #"%#",[lines objectAtIndex:e]];
[Eventarray addObject:Periode];
}
[string1 deleteCharactersInRange:NSMakeRange([string1 length]-1, 1)];
}
for(int i=0;i<[Eventarray count]; i++)
{
NSLog(#"Eventarray: %#", [Eventarray objectAtIndex:i]);
}
The array looks like this:
2013-08-12 13:31:35.375 xxxx[3809:207] PublishedRoster
2013-08-12 13:31:35.376 xxxx[3809:207] Period:
2013-08-12 13:31:35.377 xxxx[3809:207] 25Jul2013-08Sep2013
I tried everything but I don't know whats wrong. What am I missing?
Try using NSRange
If you want to search for a substring
NSString *homebrew = #"Rajneesh071";
NSRange range = [homebrew rangeOfString:#"Raj"];
// Did we find the string "Raj" ?
if (range.length > 0)
NSLog(#"Range is: %#", NSStringFromRange(range));
In your code you can do it like.
for(int i=0;i<[lines count]; i++)
{
NSRange stringRange = [[lines objectAtIndex:i] rangeOfString:#"Period:" options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[Eventarray addObject:Periode];
}
}

Displaying an array in xcode

I am trying to display the an array with different factors of a number ("prime"). But instead of giving me the int numbers I always get 0,1,2,3,4,5,... .
factors.text = #"";
int factorsNumber;
NSMutableArray *array;
array = [NSMutableArray arrayWithCapacity:5];
for (factorsNumber=1; factorsNumber<=prime; factorsNumber++) {
if (prime%factorsNumber == 0) {
[array addObject:[NSString stringWithFormat:#"%d", factorsNumber]];
}
}
for (int i = 0; i < [array count]; i++) {
[array replaceObjectAtIndex:1 withObject:#"4"];
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
factors.text = [factors.text stringByAppendingString:temp];
}
Replace
NSString *temp = [NSString stringWithFormat:#"%d, ", i, [[array objectAtIndex:i] intValue]];
with
NSString *temp = [NSString stringWithFormat:#"%d, ", [[array objectAtIndex:i] intValue]];
The problem was you were only printing the array index, not the value.

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.