how to get first three characters of an NSString? - objective-c

How can I return the first three characters of an NSString?

mystr=[mystr substringToIndex:3];
Be sure your string has atleast 3 ch.. o.e. it will crash the app.
Here are some other links to check NSsting operations...
Link1
Link2
Apple Link

First, you have to make sure that the string contains at least 3 characters:
NSString *fullString = /* obtain from somewhere */;
NSString *prefix = nil;
if ([fullString length] >= 3)
prefix = [fullString substringToIndex:3];
else
prefix = fullString;
substringToIndex: will throw an exception if the index you provide is beyond the end of the string.

the right way is:
text = [text substringToIndex:NSMaxRange([text rangeOfComposedCharacterSequenceAtIndex:2])];
substringToIndex of NSString is indexing by code unit, emoji takes two code units.
make sure check the index yourself.

Related

Objective C remove end of string after certain character [duplicate]

This question already has answers here:
Remove Characters and Everything After from String
(2 answers)
Closed 8 years ago.
I can't seem to find the answer to this anywhere. I can do it in c but objective c is difficult.
I want to cut the end of a string after a certain character
so user#example.com will become user (cut at '#')
How do I do this?
This will give you the first chunk of text that comes before your special character.
NSString *separatorString = #"#";
NSString *myString = #"user#example.com";
NSString *myNewString = [myString componentsSeparatedByString:separatorString].firstObject;
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You can use a combination of substringToIndex: and rangeOfString: methods, like this:
NSString *str = #"user#example.com";
NSRange pos = [str rangeOfString:#"#"];
if (pos.location != NSNotFound) {
NSString *prefix = [str substringToIndex:pos.location];
}
Notes:
You need to check the location against NSNotFound to ensure that the position is valid.
substringToIndex: excludes the index itself, so the # character would not be included.

Combining Korean characters in Objective-C

I have been scratching my head over this.
I want to combine two Korean characters into a single one.
ㅁ + ㅏ = 마
How would I go about doing this with NSString?
Edit:
zaph's solution works with two characters. But I am stumped on how to combine more than 2 .
ㅁ + ㅏ + ㄴ = 만
But
NSString *s = #"ㅁㅏㄴ";
NSString *t = [s precomposedStringWithCompatibilityMapping];
NSLog(#"%#", t);
prints out
마ㄴ
Edit 2:
I looked around a bit more and it seems a bit more involved. A character like '만' is made up of 3 parts. The initial jamo, medial jamo and a final jamo. These need to be combined to map to a code point in the Hangul Syllables, using the equation below.
((initial * 588) + (medial * 28) + final) + 44032
This blog post has a very good explanation.
Use '- (NSString *)precomposedStringWithCompatibilityMapping'.
NSString *tc = #"ㅁㅏ";
NSLog(#"tc: '%#'", tc);
NSString *cc = [tc precomposedStringWithCompatibilityMapping];
NSLog(#"cc: '%#'", cc);
NSLog output:
tc: 'ㅁㅏ'
cc: '마'
See Apple's Technical Q&A QA1235: Converting to Precomposed Unicode
They're actually different Unicode characters. ㅁ (\u3141) is part of the "Hangul compatibility jamo" block, and those characters are meant to appear on their own (say, when you want to illustrate an individual jamo). The actual character you want is \u1106. For example, here is \u1106 followed by \u1161, individually copied and pasted from a Unicode table: 마. As you can see, those compose into the character you want.
It's simple:
NSString *first = #"ㅁ";
NSString *second = #"ㅏ";
NSString *combinedStr = [first stringByAppendingString:second];
NSLog(#"%#", combinedStr); // ㅁㅏ

\n does not skip to next line in NSString

NSMutableString *a = #"Hi";
NSMutableString *b =[a stringByAppendingString:#"\n\n Hi Again"];
The above doesn't give an error but does not put "Hi Again" on the next line. Why?
EDIT2
I realised after posting, that the OP had NSString in the title but put NSMutableString in the code. I have submitted an edit to change the NSMutableString to NSString.
I will leave this as it still maybe helpful.
Well I am surprised that does not give an error, because you are giving a NSMutableString a NSString.
You need to read the Documentation on NSMutableStrings.
to give you an idea
//non mutable strings
NSString *shortGreetingString = #"Hi";
NSString *longGreetingString = #"Hi Again";
/*mutable string - is created and given a character capacity The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string
*/
NSMutableString *mutableString= [NSMutableString stringWithCapacity:15];
/*The mutableString, now uses an appendFormat to construct the string
each %# in the Parameters for the appendFormat is a place holder for values of NSStrings
listed in the order you want after the comma.
Any other charactars will be included in the construction, in this case the new lines.
*/
[mutableString appendFormat:#"%#\n\n%#",shortGreetingString,longGreetingString];
NSLog (#"mutableString = %#" ,mutableString);
[pool drain];
I think this might help you. You'd rather to use '\r' instead of '\n'
I also had a similar problem and found \n works in LLDB but not in GDB
Try using NSString. You could use:
NSString *a = [NSString stringWithFormat:#"%#\n\n%#", #"Hi", #"Hello again"]
If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0
myView.numberOfLines=0;

How to get a single NSString character from an NSString

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.
This is the code I use to get a single character at index it:
[[s substringToIndex:i] substringToIndex:1]
Is there a better way to do it?
This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.
NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
If you just want to get one character from an a NSString, you can try this.
- (unichar)characterAtIndex:(NSUInteger)index;
Used like so:
NSString *originalString = #"hello";
int index = 2;
NSString *theCharacter = [NSString stringWithFormat:#"%c", [originalString characterAtIndex:index-1]];
//returns "e".
Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.
Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.
NSMutableString *myString=[NSMutableString stringWithFormat:#"Malayalam"];
NSMutableString *revString=#"";
for (int i=0; i<myString.length; i++) {
revString=[NSMutableString stringWithFormat:#"%c%#",[myString characterAtIndex:i],revString];
}
NSLog(#"%#",revString);

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.