How to random sort a NSString - iphone

NSMutableString *str =#"abcdefg123";
I want random the every character to a new String like this #"f1ad2g3be2".

NSMutableString *str1 = [[NSMutableString alloc]initWithString:str];
NSMutableString *str2 = [[NSMutableString alloc] init];
while ([str1 length] > 0) {
int i = arc4random() % [str1 length];
NSRange range = NSMakeRange(i,1);
NSString *sub = [str1 substringWithRange:range];
[str2 appendString:sub];
[str1 replaceOccurrencesOfString:sub withString:#"" options:nil range:range];
}
[str1 release];
str2 is what u want

Quite simple. First you must break up the characters into an array to work with. Then you swap the letters X many times, I choose to do this so every character will be swapped
NSString *str =#"abcdefg123";
int length = str.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
NSString *results = [letters componentsJoinedByString:#""];
NSLog(#"The string before : %#", str);
NSLog(#"This is the string now : %#", results);

Related

Separate words from a NSString which are preceded by a hashtag

I have a NSString, for example:
"Had a #great time at the #party last night."
I want to separate this into an array, as so:
"Had a "
"#great"
" time at the "
"#party"
" last night."
How could i do this?
NSString *str = #"Had a #great time at the #party last night.";
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSArray *array = [str componentsSeparatedByString:#"#"];
NSMutableString *retStr= [[NSMutableString alloc] initWithString:[array objectAtIndex:0]];
[arr addObject:retStr];
for(int i=1 ; i<[array count];i++)
{
NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:#" "];
{
NSMutableString *retStr= [[NSMutableString alloc]init];
for (int i = 0;i< [array1 count]; i++)
{
if(i==0)
{
[retStr appendFormat:#" #%# ",[array1 objectAtIndex:i]];
[arr addObject:retStr];
retStr= [[NSMutableString alloc]init];
}
else
{
[retStr appendFormat:#"%# ",[array1 objectAtIndex:i]];
}
}
[arr addObject:retStr];
}
}
NSLog(#"%#",arr);
You will get the corect output as you want
try like this it'l helps you,
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#" "];
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF contains '#'"];
NSArray *b = [arr filteredArrayUsingPredicate:p];
NSLog(#"%#",b);
above predicate will returns the words which are not containg '#' symbol
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF like '#*'"];
it'l returns the words which are not started with the letter '#'
O/P:-
(
how,
are
)
EDIT:-
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#"#"];
NSMutableArray *result=[[NSMutableArray alloc]initWithObjects:[arr objectAtIndex:0], nil];
for(int i=1;i<[arr count];i++){
[result addObject:[NSString stringWithFormat:#"#%#",[arr objectAtIndex:i]]];
}
NSLog(#"%#",result);
O/P:-
(
"how are ",
"#you ",
"#friend"
)
Try to use this regexp: (#.+?\\b)|(.+?(?=#|$))
It find words which begins with hashtag and subsequences which ends with hashtag
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((#.+?\\b)|(.+?(?=#|$)))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult* match in matches ) {
NSLog(#"%#", [string substringWithRange:[match range]]);
}
Output:
2013-04-29 16:57:51.688 Had a
2013-04-29 16:57:51.689 #great
2013-04-29 16:57:51.690 time at the
2013-04-29 16:57:51.691 #party
2013-04-29 16:57:51.692 last night.
If you want to do it efficiently in a single pass on the string you can try something like (scratch code - test for bugs/boundary cases etc...):
int main (int argc, const char * argv[])
{
NSString *msg = #"Had a #great time at the #party last night.";
Boolean inTag = NO;
NSMutableArray *segments = [[NSMutableArray alloc] init];
NSUInteger idx = 0;
NSUInteger i=0;
for (; i < [msg length]; i++)
{
unichar ch = [msg characterAtIndex:i];
if (inTag && ch == ' ')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = NO;
}
if (ch == '#')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = YES;
}
}
if (i > idx)
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx - 1)]];
}
for(NSString *seg in segments)
{
NSLog(#"%#", seg);
}
}
This outputs:
2013-04-29 08:34:34.984 Craplet[95591:707] Had a
2013-04-29 08:34:34.986 Craplet[95591:707] #great
2013-04-29 08:34:34.986 Craplet[95591:707] time at the
2013-04-29 08:34:34.987 Craplet[95591:707] #party
2013-04-29 08:34:34.987 Craplet[95591:707] last night
Try this:
for (int i=0;i<[YourArray count];i++) {
NSString * mystr=[YourArray objectAtIndex:i];
NSString *temp=[mystr substringToIndex:1];
if (![temp isEqualToString:#"#"]) {
//add your string in new array and use this arry.....
}
}
try this code
for (int i=0;i<[YourArray count];i++) {
NSString * str=[YourArray objectAtIndex:i];
NSString *myString=[str substringToIndex:1];
NSString *stringfinal = [myString
stringByReplacingOccurrencesOfString:#"#" withString:#""];
}
Try using regular expressions. With this code you'll be able to extract the hashtags:
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((?:#){1}[\\w\\d]{1,140})" options:0 error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for ( NSTextCheckingResult* match in matches )
{
NSString * hashtag = [string substringWithRange:[match range]];
NSLog(#"match: %#", hashtag);
}
With this, you'll be able to build up the array result you're looking for.
Try
NSString *string = #"Had a #great time at the #party last night.";
NSArray *components = [string componentsSeparatedByString:#" "];
NSMutableArray *formattedArray = [NSMutableArray array];
NSMutableString *mutableString = [NSMutableString string];
for (NSString *string in components)
{
if (![string hasPrefix:#"#"]){
if (!mutableString){
mutableString = [NSMutableString string];
}
[mutableString appendFormat:#" %#",string];
}else{
if (mutableString) {
[formattedArray addObject:mutableString];
mutableString = nil;
}
[formattedArray addObject:string];
}
}
if (mutableString) {
[formattedArray addObject:mutableString];
}
NSLog(#"%#",formattedArray);
EDIT :
(
" Had a",
"#great",
" time at the",
"#party",
" last night."
)
One-pass solution with NSScanner
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject:s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
}
result:
(
"Had a ",
"#great",
"time at the ",
"#party",
"last night."
)
if you want to preserve the leading whitespace, alter it slightly to
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL firstSegment = YES;
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject: (!firstSegment) ? [#" " stringByAppendingString:s] : s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
firstSegment = NO;
}
result:
(
"Had a ",
"#great",
" time at the ",
"#party",
" last night."
)

Reverse strings in array objectivec [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse NSString text
i am new on objectovec. i have a array having strings. how to reverse each string?
which method of NSArray and NSstring will help me out?
i want reversed string in the array.
thanks
Create a method that will return a reversed string.
-(NSString *)reverseString:(NSString *)string{
NSString *reverseString=[NSString new];
for (NSInteger i=string.length-1; i>-1; i--) {
reverseString=[reverseString stringByAppendingFormat:#"%c",[string characterAtIndex:i]];
}
return reverseString;
}
In your any of the method :
NSMutableArray *names=[NSMutableArray arrayWithObjects:#"anoop",#"johnson",#"wasim",nil];
for (NSInteger i=0; i<names.count; i++) {
names[i]=[self reverseString:names[i]];
}
NSLog(#"%#",names);
Hope this help
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
AnOther way for revers string NSStringEnumerationOptions
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Use
unichar c[yourstring.Length];
NSRange raneg={0,yourstring.Length};
[yourstring getCharacters:c range:raneg];
//c will be an array of your string do what ever you wish
Use this one to reverse your string and then store back to your array at same index.
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%c", [string characterAtIndex:length]];
}
return reversedString;
}
But if you have mutable string then you can create a category
#interface NSMutableString (Reverse)
- (void)reverseString;
#end
#implementation NSMutableString (Reverse)
- (void)reverseString {
for (int i = 0; i < self.length/2; i++) {
int l = self.length - 1 - i;
NSRange iRange = NSMakeRange(i, 1);
NSRange lRange = NSMakeRange(l, 1);
NSString *iStr = [self substringWithRange:iRange];
NSString *lStr = [self substringWithRange:lRange];
[self replaceCharactersInRange:iRange withString:lStr];
[self replaceCharactersInRange:lRange withString:iStr];
}
}
#end
And then you can use this category method like this
NSArray *arr = [NSArray arrayWithObjects:[#"hello" mutableCopy], [#"Do it now" mutableCopy], [#"Test string, 123 123" mutableCopy], nil];
NSLog(#"%#",arr);
[arr makeObjectsPerformSelector:#selector(reverseString)];
NSLog(#"%#",arr);

Change the position of character in string

I have a two string like "SANFRANSICO" and "CHICAGO"
Now i want to make it like the string is in reverse but in a single string like "OOCGIASCNIAHRCFNAS"
I have done code but it gives me wrong result
check out my code
- (NSString *)changeString1:(NSString *)string string2:(NSString *)string2{
int first = [string length];
int second = [string2 length];
int total = first+second;
NSMutableString *str = [[NSMutableString alloc] init];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for (int i=0; i<total+1; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j+1]];
NSLog(#"222 %d %#",j+1, ichar );
[str appendString:ichar];
check = YES;
}
}
else {
int j = i/2;
if(check == YES){
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
NSLog(#"1111 %d %#",j, ichar );
[str appendString:ichar];
}
}
}
return str;
}
I found the answer very soon after post this question sorry for posting this question
check out my answer
- (NSString *)changeString1:(NSString *)string string2:(NSMutableString *)string2{
int first = [string length];
int second = [string2 length];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for(int i =second; i<first; i ++){
[string2 appendString:#" "];
}
int total = first*2;
NSMutableString *str = [[NSMutableString alloc] init];
for (int i=0; i<total; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
else {
int j = i/2;
if(j < first){
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
}
NSLog(#"str %#", str);
return str;
}

nsstring replace string in range

I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end

Subtracting 2 strings

I have a string say for example #"012" and I have another string #"02". How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
Even shorter:
NSString* s1 = #"012";
NSString* s2 = #"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:#""];
NSLog(#"Final: %#", final);
This preserves the order of the characters in the original string.
You could do something like this;
NSString *s1 = #"012";
NSString *s2 = #"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:#"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
You're trying to do a set operation, so use sets.
{
NSString* s1 = #"012";
NSString* s2 = #"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(#"set1: %#", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(#"result: %#", result);
}
I simply used "componentsSeparatedByString"
NSString *s1 = #"abc";
NSString *s2 = #"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:#""];