ios method to insert spaces in string - iphone

In my app I download a file from amazon's s3, which does not work unless the file name has no spaces in it. For example, one of the files is "HoleByNature". I would like to display this to the user as "Hole By Nature", even though the file name will still have no spaces in it.
I was thinking of writing a method to search through the string starting at the 1st character (not the 0th) and every time I find a capital letter I create a new string with a substring until that index with a space and a substring until the rest.
So I have two questions.
If I use NSString's characterAtIndex, how do I know if that character is capital or not?
Is there a better way to do this?
Thank you!

Works for all unicode uppercase and titlecase letters
- (NSString*) spaceUppercase:(NSString*) text {
NSCharacterSet *set = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableString *result = [NSMutableString new];
for (int i = 0; i < [text length]; i++) {
unichar c = [text characterAtIndex:i];
if ([set characterIsMember:c] && i!=0){
[result appendFormat:#" %C",c];
} else {
[result appendFormat:#"%C",c];
}
}
return result;
}

I would not go to that approach because I know you can download files with spaces try this please when you construct the NSUrl object
#"my_web_site_url\sub_domain\sub_folder\My%20File.txt
this will download "My File.txt" from the URL provided. so basically you can replace all spaces in the URL with %20
reference:
http://www.w3schools.com/tags/ref_urlencode.asp

Got it working with Jano's answer but using the isupper function as suggested by Richard J. Ross III.
- (NSString*) spaceUppercase:(NSString*) text
{
NSMutableString *result = [NSMutableString new];
[result appendFormat:#"%C",[text characterAtIndex:0]];
for (int i = 1; i < [text length]; i++)
{
unichar c = [text characterAtIndex:i];
if (isupper(c))
{
[result appendFormat:#" %C",c];
}
else
{
[result appendFormat:#"%C",c];
}
}
return result;
}

Related

Replacing instances of a character with two different characters in Objective-C

I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as "This is a message with $specially formatted$ content".
However, I need to change the '$' at the start of the special formatting with a '[' and the '$' at the end with ']'. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!
Is there a simple way to recognise a substring encapsulated by '$' and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple '$' substrings.
Thanks!
You can use regular expressions:
NSMutableString *str = [#"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#"[$1]"];
NSLog(#"%#", str);
// Output:
// Hello [World], foo [bar].
The pattern #"\\$([^$]*)\\$" searches for
$<zero_or_more_characters_which_are_not_a_dollarsign>$
and all occurrences are then replaced by [...]. The pattern contains so many backslashes because the $ must be escaped in the regular expression pattern.
There is also stringByReplacingMatchesInString if you want to create a new string instead of modifying the original string.
I think replaceOccurrencesOfString: won't work cause you have start$ and end$.
But if you seperate the Strings with [string componentsSeperatedByString:#"$"] you get an Array of substrings, so every second string is your "$specially formatted$"-string
This should work!
NSString *str = #"This is a message with $specially formatted$ content";
NSString *original = #"$";
NSString *replacement1 = #"[";
NSString *replacement2 = #"]";
BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
start = !start;
rOriginal = [str rangeOfString: original];
}
NSLog(#"%#", str);
Enjoy Programming!
// string = #"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:#"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
[out appendString:components[i]];
[out appendString: (i % 2) ? #"]" : #"[" ];
}
// out = #"This is a [special markup] sentence."
Try this one
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
if ([string characterAtIndex:i]=='$') {
if (open) {
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"["];
open=!open;
}
else{
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"]"];
open=!open;
}
}
}
NSLog(#"-->%#",string);
Output:
-->This is a message with [specially formatted] content. This is a message with [specially formatted] content

How to split the text of a UITextField into individual characters

I have a UITextField and suppose there are 5 characters in this textbox for e.g. hello.
Now I want to divide this word into single character i.e. 'h','e','l','l','o';
then how can I perform this kind of action.
Any help will be appreciated.
First get the string value from the textfield:
NSString *text = myTextField.text;
Then you can iterate each character:
NSUInteger len = [text length];
for (NSUInteger i = 0; i < len; i++)
{
unichar c = [text characterAtIndex:i];
// Do something with 'c'
}
Just use the NSString method UTF8String
const char *str = [textField.text UTF8String];
You then have an array of UTF8 chars
NOTE: ensure you are happy with the UTF8 encoding i.e. no non standard characters
I think using the for loop is a good idea, but to get exactly what you asked for, use -getCharacters:range:. Here is an example:
- (void)testGetCharsInRange
{
NSString *text = #"This is a test string, will it work?";
unichar *chars = calloc([text length], sizeof(unichar));
[text getCharacters:chars range:NSMakeRange(0, [text length])];
STAssertEquals(chars[[text length] - 1], (unichar)'?', nil);
free(chars);
}

Objective-C: Find consonants in string

I have a string that contains words with consonants and vowels. How can I extract only consonants from the string?
NSString *str = #"consonants.";
Result must be:
cnsnnts
You could make a character set with all the vowels (#"aeiouy")
+ (id)characterSetWithCharactersInString:(NSString *)aString
then use the
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
method.
EDIT: This will only remove vowels at the beginning and end of the string as pointed out in the other post, what you could do instead is use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
then stick the components back together. You may also need to include capitalized versions of the vowels in the set, and if you want to also deal with accents (à á è è ê ì etc...) you'll probably have to include that also.
Unfortunately stringByTrimmingCharactersInSet wont work as it only trim leading and ending characters, but you could try using a regular expression and substitution like this:
[[NSRegularExpression
regularExpressionWithPattern:#"[^bcdefghjklmnpqrstvwx]"
options:NSRegularExpressionCaseInsensitive
error:NULL]
stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""]
You probably want to tune the regex and options for your needs.
Possible, for sure not-optimal, solution. I'm printing intermediate results for your learning. Take care of memory allocation (I didn't care). Hopefully someone will send you a better solution, but you can copy and paste this for the moment.
NSString *test = #"Try to get all consonants";
NSMutableString *found = [[NSMutableString alloc] init];
NSInteger loc = 0;
NSCharacterSet *consonants = [NSCharacterSet characterSetWithCharactersInString:#"bcdfghjklmnpqrstvwxyz"];
while(loc!=NSNotFound && loc<[test length]) {
NSRange r = [[test lowercaseString] rangeOfCharacterFromSet:consonants options:0 range:NSMakeRange(loc, [test length]-loc)];
if(r.location!=NSNotFound) {
NSString *temp = [test substringWithRange:r];
NSLog(#"Range: %# Temp: %#",NSStringFromRange(r), temp);
[found appendString:temp];
loc=r.location+r.length;
} else {
loc=NSNotFound;
}
}
NSLog(#"Found: %#",found);
Here is a NSString category that does the job:
- (NSString *)consonants
{
NSString *result = [NSString stringWithString:self];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"aeiou"];
while(1)
{
NSRange range = [result rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
break;
result = [result stringByReplacingCharactersInRange:range withString:#""];
}
return result;
}

How to comapare the string character by character in Objective c?

Iam developing one applciation.In that i want to comapare the every character of string with other character.So please tell me how to do that one.
Use characterAtIndex: function of NSString to extract the character by index.
- (unichar)characterAtIndex:(NSUInteger)index
for (int i=0; i<[string length]; i++) {
char = [string characterAtIndex:i];
NSString *charString = [NSString stringWithFormat:#"%c", char];
if ([charString isEqualToString:comparisonString]) {
//match
}
else {
//no match
}
}
if you want to compare a string. Using isEqualToString method.
NSMutableString *str = [[NSMutableString alloc] initWithString:#"a"];
if([str isEqualToString:#"a"]){
// match
}
else{
// not match
}

Checking for multiple characters in nsstring

i have a string and i want to check for the multiple characters in this string the following code i working fine for one character how to check for the multiple characters.
NSString *yourString = #"ABCCDEDRFFED"; // For example
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charactersToCount = #"C" // For example
NSString *charactersFromString;
if (!([scanner scanCharactersFromSet:charactersToCount intoString:&charactersFromString])) {
// No characters found
NSLog(#"No characters found");
}
NSInteger characterCount = [charactersFromString length];
UPDATE: The previous example was broken, as NSScanner should not be used like that. Here's a much more straight-forward example:
NSString* string = #"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:#"ABC"];
NSUInteger characterCount;
NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
unichar character = [yourString characterAtIndex:i];
if ([characters characterIsMember:character]) characterCount++;
}
NSLog(#"Total characters = %d", characterCount);
Have a look at the following method in NSCharacterSet:
+ (id)characterSetWithCharactersInString:(NSString *)aString
You can create a character set with more than one character (hence the name character set), by using that class method to create your set. The parameter is a string, every character in that string will end up in the character set.
Also look up NSCountedSet. It can help you keep count of multiple instances of the same character.
For example, from the docs:
countForObject:
Returns the count associated with a given object in the receiver.
- (NSUInteger)countForObject:(id)anObject
Parameters
anObject
The object for which to return the count.
Return Value
The count associated with anObject in the receiver, which can be thought of as the number of occurrences of anObject present in the receiver.