How to do a backwards search to find the 2nd space/blank and replace it with another string? - iphone

it's me again. I've asked a question similar to this just awhile ago but this question is a bit more complex. I was planning on using RegexKitLite to do what I needed to do but I believe this can be done with out it. I have a NSString that has some words with spaces/blanks in it and I'm wanting to get the very last space in the string that is to the left of the last word. Example String below:
NSString *string = #"Here is an example string HELLO ";
As you can see in the string above there is a space/blank at the very end of the string. I'm wanting to be able to get the space/blank to the left of HELLO and replace it with my own text/string. I'm working on using the NSString's NSBackwardsSearch but it's not working.
NSString *spaceReplacement = #"text that i want";
NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:#" " withString:spaceReplacement];
NSLog(#"%#", replaced);
Any help would help, I'm just tired of trying to fix this thing, it's driving me bonkers. I thought I could do this with RegexKitLite but the learning curve for that is too steep for me considering my timeframe I'm working with. I'm glad Jacob R. referred me to use NSString's methods :-)

This solution assumes you always have a space at the end of your string... it should convert
Here is an example string HELLO
... to:
Here is an example stringtext that i wantHELLO
... since that's what I understood you wanted to do.
Here's the code:
NSString *string = #"Here is an example string HELLO ";
NSRange rangeToSearch = NSMakeRange(0, [string length] - 1); // get a range without the space character
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" " options:NSBackwardsSearch range:rangeToSearch];
NSString *spaceReplacement = #"text that i want";
NSString *result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace withString:spaceReplacement];
The trick is to use the [NSString rangeOfString:options:range:] method.
Note: If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
Disclaimer: I haven't tested the code, but it should compile and work just fine.

Something like this should work:
NSString *string = #"Here is an example string HELLO ";
if ([string hasSuffix:#" "]) {
NSString *spaceReplacement = #"text that i want";
NSString *replacedString = [[string substringToIndex:
[string length]] stringByAppendingString:spaceReplacement];
NSLog(#"replacedString == %#", replacedString);
}

To solve #Senseful note
If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
I had added one line into code that helps in such situations and make code more universal:
// Some income sting
NSString * string = #"Here is an example string HELLO ";
// clear string from whitespace in end on string
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange rangeToSearch = NSMakeRange(0, [string length]);
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" "
options:NSBackwardsSearch
range:rangeToSearch];
// Replaed with String
NSString * spaceReplacement = #"text that i want";
NSString * result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace
withString:spaceReplacement];

Related

How to replace two different strings in iPhone programming

I am reading CSV file in my application.
I want to replace two different strings and print as one line. for example:
string1#$string2#$string3####string4
I want to replace #$ with , and #### with \n
and want to show the result on a UILabel.
You can use stringByReplacingOccurrencesOfString:withString: method, like this:
NSString *orig = "string1#$string2#$string3####string4";
NSString *res = [orig stringByReplacingOccurrencesOfString:#"#$" withString:#" "];
res = [res stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
Note that the original string does not get changed: instead, a new instance is produced with the replacements that you requested.
use
String = [String stringByReplacingOccurrencesOfString:#"#$" withString:#","];
String = [String stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
And then
yourLabel.text=String;
Try this
NSString *string = #"####abc#$de";
string = [string stringByReplacingOccurrencesOfString:#"####" withString:#"\n"];
string = [string stringByReplacingOccurrencesOfString:#"#$" withString:#","];
Hope it helps you

Get first sentence of textview

I am trying to get the first sentence of a text view. I have the following code but am getting an out of bounds error. Thank You. Or are there any ways that aren't really complex.
-(IBAction)next:(id)sender
{
NSRange ran = [[tv.text substringFromIndex:lastLocation] rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * getRidOfFirstHalfString = [[tv.text substringFromIndex:lastLocation] substringToIndex:ran.location];
NSLog(#"%#",getRidOfFirstHalfString);
lastLocation+=getRidOfFirstHalfString.length;
}
How about:
NSString *finalString = [[tv.text componentsSeparatedByString:#"."] objectAtIndex:0] // Get the 1st part (left part) of the separated string
Go through the textview's text and divide the text into separate components where you find a period by calling componentsSeperatedByString on tv.text. You want the first sentence, which would be the 0th object in the array.
I know you've already accepted an answer to this question, but you might want to consider using the text view's tokenizer instead of just searching for the string ". " The tokenizer will automatically handle punctuation like !, ?, and closing quotes. You can use it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextRange *range = [tokenizer rangeEnclosingPosition:textView.beginningOfDocument
withGranularity:UITextGranularitySentence
inDirection:UITextStorageDirectionForward];
NSString *firstSentence = [textView textInRange:range];
If you want to enumerate all of the sentences, you can do it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *start = textView.beginningOfDocument;
while (![start isEqual:textView.endOfDocument]) {
UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularitySentence inDirection:UITextStorageDirectionForward];
NSString *sentence = [textView textInRange:[textView textRangeFromPosition:start toPosition:end]];
NSLog(#"sentence=%#", sentence);
start = end;
}
Try checking that the substring was actually found.
NSRange ran = [tv.text rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * selectedString = [tv.text substringToIndex:ran.location];
NSLog(#"%#",selectedString);
}
You could alternatively try using NSScanner like this:
NSString *firstSentence = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:tv.text];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"."];
[scanner scanUpToCharactersFromSet:set intoString:&firstSentence];
I'm not sure if you want this, but since you want the first sentence, you could append a period (you probably know how to do this, but it doesn't hurt to show it anyway):
firstSentence = [firstSentence stringByAppendingFormat:#"."];
Hope this helps!
PS: If it didn't work for you, maybe the text view doesn't actually contain any text.

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

How to remove whitespace in a string?

I have a string say "Allentown, pa"
How to remove the white space in between , and pa using objective c?
This will remove all space from myString.
NSString *newString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
Here is a proper and documented way of removing white spaces from your string.
whitespaceCharacterSet Apple Documentation for iOS says:
Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
+ (id)whitespaceCharacterSet
Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
Discussion
This set doesn’t contain the newline or carriage return characters.
Availability
Available in iOS 2.0 and later.
You can use this documented way:
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps you.
If you need any more help then please let me know on this.
Probably the solution in one of the answers in Collapse sequences of white space into a single character and trim string:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
NSLog(#"Value of the text field is %#",trimmedString);
myStr = [myStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *sample = #" string with whitespaces";
NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
In my case NSString was added Zero Width Space(i i used some library). so solution worked for me.
NSMutableString *newString=[[newString stringByReplacingOccurrencesOfString:#"\u200B" withString:#""] mutableCopy];
#"\u200B" is Zero width space character value.
Here is the proper way to remove extra whitespaces from string which is coming in between.
NSString *yourString = #"Allentown, pa";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:#" "];
you can use remove function to remove any substring from the string
- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input {
return [input stringByReplacingOccurrencesOfString:textToRemove withString:#""];
}
I have tried all the solutions here, none of them could remove the whitespace generated by the Chinese PinYin Input method.
After some debugging, I found this working:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\342\200\206" withString:#""];
I have googled what the '\342\200\206' is, but failed.
Whatever, it works for me.
Hi there is the swift version of the solution with extension :
extension String{
func deleteSpaces() -> String{
return self.stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
And Just call
(yourString as! String).deleteSpaces()
Swift 3:
var word: String = "Hello world"
let removeWhiteSpace = word.stringByRemovingWhitespaces
word = "Helloworld"

How to replace a character in NSString without inserting a space?

Let's assume I have the string
NSString* myString = #"Hello,";
How can I remove the comma without leaving a space? I have tried:
NSString* newString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
and
NSString* newString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
But both are leaving spaces.
I just ran the following as a test
NSString * myString = #"Hello,";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%#xx",newString);
And I get 2010-04-05 18:51:18.885 TestString[6823:a0f] Helloxx as output. There is no space left.
NSString *newString = [myString substringToIndex:5];
That will ensure that there are only 5 characters in the string, but beware that this will also throw an exception if there are not at least 5 characters in the string to begin with. How are you handling this string? Is it being displayed to the user? Is it being written to a file? The code that you posted does not reproduce the error, so perhaps you should post the code that you are having a problem with.
the other way u can use.. by stringByReplacingCharactersInRange
token = [token stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:#"*"];
"token"is your want to replace the NSString and "i" is you want to change NSString by "*"