How to cut a string at a specific point? [duplicate] - objective-c

This question already has answers here:
NSString tokenize in Objective-C
(9 answers)
Closed 10 years ago.
So, I have a vast quantity of NSStrings and my problem is I need to cut them into smaller strings at a specific point. This may sound complicated but what I need basically is this:
NSString *test =" blah blah blah - goo goo goo.";
NSString *str1 = "blah blah blah ";
NSString *str2 = "goo goo goo";
How do I code for when there's a hyphen for the string to just cut off there. Is there a way to do this? I found ways to cut of the string after a certain amount of letters but I need it at the hyphen every time.

NSArray *arr = [string componentsSeparatedByString:#"-"];
should do the trick.

You could do this many ways. Two answers above show a few approaches. Many Objective-C solutions will include NSRange usage. You could also do more flexible things with NSScanner or NSRegularExpression.
There is not going to be one right answer.

NSString *cutString = [text substringFromIndex:3];
cutString = [text substringToIndex:5];
cutString = [text substringWithRange:NSMakeRange(3, 5)];

Related

Delete whiteSpaces in Objective C [duplicate]

This question already has an answer here:
How do you remove extra empty space in NSString?
(1 answer)
Closed 6 years ago.
I am trying to delete the extra white spaces in my string
for exemple
NSString *mystring= #" Alex mona ok";
so after deleting the extra white spaces mastering should look like this
// deleting the first spaces, middle spaces and the last spaces
"Alex mona ok"
Unfortunately, Cocoa's split method is not versatile enough to remove duplicate separators on its own, so you need to write quite a bit of code:
Split your string into words on whitespace
Remove empty entries created for adjacent separators
Join the array back on a single space
Here is the same thing coded in Objective-C:
NSString *mystring= #" Alex mona ok";
NSMutableArray *words = [[mystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
[words removeObject:#""];
NSString *res = [words componentsJoinedByString:#" "];
If you only need to remove a certain character like a space use this:
[mystring stringByReplacingOccurrencesOfString:#" " withString:#""]
If you need to remove tabs, spaces, etc. use:
NSArray* newstring = [mystring componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [newstring componentsJoinedByString:#" "];
This removes all whitespace and then joins the components of the non whitespace back together.

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); // ㅁㅏ

clean a string extracting all the non numeric characters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm quite new in Objective C. I'm trying to convert the following string 5896.3454A into a numeric string 58963454. Any idea how to do it.
I have been trying with NSScanner class, but I'm not sure, whether this is the best approach.
One possible solution would be to use a string replacement with regular expressions:
NSString *mixed = #"5896.3454A";
NSString *pattern = #"\\D"; // Pattern for "not a digit"
NSString *digitsOnly = [mixed stringByReplacingOccurrencesOfString:pattern
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [mixed length])];
Objective-C contains a lot of little tricks. Here is a silly one to solve your problem.
NSString *string = #"5896.3454A";
NSCharacterSet *digits = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
NSCharacterSet *nonDigits = [digits invertedSet];
NSArray *digitSubstrings = [componentsSeparatedByCharactersInSet:nonDigits];
NSString *result = [digitSubstrings componentsJoinedByString:#""];
result will have only the digits in string.
I create a character set with all the digits. I use invertedSet to get a set with every character other than the digits. This is straight forward, next is the silly part. Next I split the string into an array of substring. This will have the effect of stripping out all the non digit characters, but all the digits are broken up into substrings. In this case, digitSubstrings will be #[#"5896", #"3454", #""]. Not a problem, I join all the substrings back together to create the final string.
You can do it also by
yourString mentioned in your question
NSInteger newInt = [ [ [ yourString stringByReplacingOccurrencesOfString:#"." withString:#""] stringByReplacingOccurrencesOfString:#"A" withString:#""] integerValue];
ADDED: NSInteger newInt = [ [ #"123.123A" stringByReplacingOccurrencesOfString:#"." withString:#""] integerValue]; combining NSString and NSScanner methods, integerValue ignores everything beginning with the first appearance of a character
You find it in the NSString class. Whether this is the better solution depends on the unwanted literals in your "string-number" you want to replace/delete.

Padding NSString not working

I have read that to left-pad an NSString all you need to do is this:
NSString *paddedStr = [NSString stringWithFormat:#"%-20.20# %-20.20#",
aString, anotherSting];
But, that does not work !! I don´t know why. I have tried a lot of combinations without success. Examples:
NSString *paddedStr = [NSString stringWithFormat:#"%-20s#", " ", myString];
but that way is ugly and ... ugly. It just append 20 times the char (" ") before the string (myString) and that is not what we need right?
The goal is to have an NSString formatted to present two or more columns of 20 chars each one no matter the length of the string within a row.
Example Goal Output:
Day Hour Name Age
Does anybody know how to do this right?
I'm using ARC and iOS 5.
And actually, the formatted string is going to be written to file using NSFileHandle.
Thanks to all of you folks !!
Edit:
I have noticed that this works:
NSString *str = [NSString stringWithFormat:#"%-10.10s %-10.10s",
[strOne UTF8String], [strTwo UTF8String]];
But... We don't want C-style strings either.
Here is a way to do that :
NSString *paddedStr = [NSString stringWithFormat:#"%#%#",
[#"day" stringByPaddingToLength:20
withString:#" "
startingAtIndex:0],
[#"Hour" stringByPaddingToLength:20
withString:#" "
startingAtIndex:0]];