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);
}
Related
I have an int value which I obtained from the character 爸, which is 29240. I can convert this number to hex, but I have no clue how to write the chinese character out in an NSString with only the int 29240.
Basically, what I did was:
NSString * s = #"爸";
int a = [s characterAtIndex:0];
NSLog(#"%d", a);
What it gave as output was 29240.
However, I don't know how to create an NSString that just contains 爸 from only the int 29240.
I converted 29240 into binary which gave me 7238, but I can't seem to create a method which allows me to input any integer and NSLog the corresponding character.
I can hard code it in, so that I have
char cString[] = "\u7238";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
But I'm not sure how to do it with any int.
Thanks to anyone who can help me!
To create a string from one (or more) Unicode characters use initWithCharacters:
unichar c = 29240;
NSString *string = [[NSString alloc] initWithCharacters:&c length:1];
NSString uses UTF-16 characters internally, so
this works for all characters in the "Basic Multilingual Plane", i.e. all characters up to U+FFFF. The following code works for arbitrary characters:
uint32_t ch = 0x1F60E;
ch = OSSwapHostToLittleInt32(ch); // To make it byte-order safe
NSString *s1 = [[NSString alloc] initWithBytes:&ch length:4 encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", s1);
// Output: 😎
Try out this code snippet to get you started in the right direction:
NSString *s = #"0123456789";
for (int i = 0; i < [s length]; i++) {
NSLog(#"Value: %d", [s characterAtIndex:i]);
}
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];
In my application I am converting a NSString to HexString. But I always require a fixed size(16 bytes) hex string e.g. if the length of my hex string is 15 bytes, I want it to be 16 bytes. I know that I can add zeros at the beginning of the hex string, but how to add that because simply adding a "0" is not working while I am converting it back into NSString.
You can try this code....
+ (NSString *) stringToHex:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
// [hexString [NSString stringWithFormat:#"%02x", chars[i]]]; //previous input
[hexString appendFormat:#"%02x", chars[i]]; //EDITED PER COMMENT BELOW
}
free(chars);
return [hexString autorelease];
}
I hope this will help you.
happy coding.
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;
}
I have implemented some code to convert a NSString of "text" to an NSString of (ASCII) ints, like so:
#"Hello" is converted to #"72 101 108 108 111"
However, I am having quite a bit of difficulty doing the opposite. Starting with a string of ints (with the spaces) and converting back to the plain string of text.
What I need: #"72 101 108 108 111" must be converted to #"Hello"
I have tried breaking up the input string into an int array, iterating through it, and using repeatedly the following:
[NSString stringWithFormat:#"%c", decCharArray[i]]
However, the problem with that is that it parses each particular digit into ASCII, converting the 7, the 2, the space, the 1, etc.
Thanks a ton in advance.
Sounds like you have the right approach. Try using [string componentsSeparatedByString:#" "] to split the string at the spaces. Then you can convert each of those to numbers, and back into strings.
There is no real magic on it. Since you'll be using ASCII, to convert an int
to a char all you have to do is an assignment, as you may already know:
char a = 65; /* a contains 'A' */
NSString has a very convenient method componentsSeparatedByString: that will
return an array of strings containing your numbers, and you can get an int
from a string with the intValue method. Thus, all you have to do is to split
the string and iterate through the components assigning their int value to a
char array. Here is an example function that does that:
NSString *
TextFromAsciiCodesString (NSString *string)
{
NSArray *components = [string componentsSeparatedByString:#" "];
NSUInteger len = [components count];
char new_str[len+1];
int i;
for (i = 0; i < len; ++i)
new_str[i] = [[components objectAtIndex:i] intValue];
new_str[i] = '\0';
return [NSString stringWithCString:new_str
encoding:NSASCIIStringEncoding];
}
And a simple use of it, with your "Hello" example:
NSString *string = #"72 101 108 108 111";
NSLog(#"%#", TextFromAsciiCodesString(string));
Actually, it's a bit different as your example was "Hell^K" :-)
You can also trying using NSString's enumerateSubstringsInRange:options:usingBlock:.
Usage
NSString * hello = #"72 101 108 108 111";
NSMutableString * result = [NSMutableString string];
[hello enumerateSubstringsInRange:NSMakeRange(0, [data length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[result appendString:[NSString stringWithFormat:#"%c", [substring intValue]]];
}];
NSLog(#"%#", result);
So NSXMLParser has problems parsing strings using the Windows-1252 encoder. Now I did find a solution on this page to convert it to NSUTF8StringEncoding. But now it bumps into characters it can't parse.
So I figured out that it will work if I would escape special characters and then transfer it back after parsing it. For example:
string = [string stringByReplacingOccurrencesOfString:#":" withString:#"__58__"];
Since it is allowed to use the _ character without getting a parser error and in NSXMLParser I can transfer the value back to it's proper character.
So is there a way I can loop through all ASCII character so I can replace all special characters (Except <, > and _ of course)?
Totally untested. I don't even know if it compiles, but it may get you on the right track. string needs to be an NSMutableString.
NSRange r = NSMakeRange(0, [string length]);
while (r.location < [string length])
{
r = [string rangeOfCharactersFromSet:[NSCharacterSet symbolCharacterSet] options:0 range:r];
if (r.location != NSNotFound)
{
NSMutableString *replacement = [[NSMutableString alloc] initWithCapacity:6];
for (NSUInteger i = r.location; i <= NSMaxRange(r); i++)
{
unichar c = [string characterAtIndex:i];
if (c != "_")
{
[replacement appendFormat:#"__%d__", (unsigned)c];
}
}
[string replaceCharactersInRange:r withString:replacement];
[replacement release]; replacement = nil;
r.location = r.location + [string length] + 1;
r.length = [string length] - r.location;
}
}
Assuming you have a NSMutableString str, you can do the following:
NSMutableString *str = ...;
[str replaceOccurrencesOfString:":" withString:#"__58__"
options:NSLiteralSearch
range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:"&" withString:#"__38__"
options:NSLiteralSearch
range:NSMakeRange(0, [str length])];
You see the pattern!
You can also just use XML entities for these values, e.g. replace & with &.
Thanks for the help everybody, this code actually solved my problem:
for (unichar asciiChar = 1; asciiChar <= 255; asciiChar++) {
NSString *stringWithAsciiChar = [NSString stringWithCharacters:&asciiChar length:1];
if (stringWithAsciiChar == nil) continue;
string = [string stringByReplacingOccurrencesOfString:stringWithAsciiChar withString:[NSString stringWithFormat:#"__%d__", asciiChar]];
}