How do i remove a substring from an nsstring? - iphone

Ok, say I have the string "hello my name is donald"
Now, I want to remove everything from "hello" to "is"
The thing is, "my name" could be anything, it could also be "his son"
So basically, simply doing stringByReplacingOccurrencesOfString won't work.
(I do have RegexLite)
How would I do this?

Use like below it will help you
NSString *hello = #"his is name is isName";
NSRange rangeSpace = [hello rangeOfString:#" "
options:NSBackwardsSearch];
NSRange isRange = [hello rangeOfString:#"is"
options:NSBackwardsSearch
range:NSMakeRange(0, rangeSpace.location)];
NSString *finalResult = [NSString stringWithFormat:#"%# %#",[hello substringToIndex:[hello rangeOfString:#" "].location],[hello substringFromIndex:isRange.location]];
NSLog(#"finalResult----%#",finalResult);

The following NSString Category may help you. It works good for me but not created by me. Thanks for the author.
NSString+Whitespace.h
#import <Foundation/Foundation.h>
#interface NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator;
#end
NSString+Whitespace.m
#
import "NSString+Whitespace.h"
#implementation NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator
{
//NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray *nonemptyComps = [[NSMutableArray alloc] init];
// only copy non-empty entries
for (NSString *oneComp in comps)
{
if (![oneComp isEqualToString:#""])
{
[nonemptyComps addObject:oneComp];
}
}
return [nonemptyComps componentsJoinedByString:seperator]; // already marked as autoreleased
}
#end

If you always know your string will begin with 'hello my name is ', then that is 17 characters, including the final space, so if you
NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];

Related

words after the same in string

I am a newbie to xcode and maybe this question is silly but I am lagging with my home work. In a file I want to read a specific character after the string.
example:
asasasasasas
wewewewewewe
xyz_ 22 aaaaaaaaaaa bbbbbbbbbbb ccccccccccccccc ddddddddddddd
fgfgfgfgfgfgfg
ererererererer
abc_ 12 bbbbbbbbbb dddddddd
jkjkjkjkjkjkjk
lalallalalalal
Mycode:
NSString *contentFile = [[NSString alloc] initWithContentsOfFile:pathFile encoding:NSUTF8StringEncoding error:nil];
NSArray *lineFile = [contentFile componentsSeparatedByString:#"\n"];
NSMutableString *xmlFile = [[NSMutableString alloc] init];
for(int i = 2; i < lineFile.count; i++)//i = 2 for don't take the 2 first line
{
if ([((NSString *)[lineFile objectAtIndex:i]) rangedOfString:#"test"].location != NSNotFound){
xmlFile = [NSString stringWithFormat:#"%#<nameTag>%#</nameTag>", xmlFile, (NSString *)[lineFile objectAtIndex:i]];
}
else if ...
}
everything works fine ..
but i want to print after xyz_ ... like :
aaaaaaaaaaa
bbbbbbbbbbb
ccccccccccccccc
ddddddddddddd
everything works fine ..
but i want to print after xyz_ ... like :
aaaaaaaaaaa
bbbbbbbbbbb
ccccccccccccccc
ddddddddddddd
I hope to have understood correctly what you want to do:
if ([([lineFile objectAtIndex:i]) rangedOfString:#"test"].location != NSNotFound)
{
xmlFile = [NSString stringWithFormat:#"%#<nameTag>%#</nameTag>", xmlFile, (NSString *)[lineFile objectAtIndex:i]];
NSString* str= [[lineFile objectAtIndex: i]stringByReplacingOccurrencesOfString: #"xyz_ " withString: #""];
NSLog(#"%#",[str stringByReplacingOccurrencesOfString: #" " withString: #"\n"]);
}
you can try this as well: (would recommend to try in a separate test app)
I am assuming your target line:
xyz_ 22 aaaaaaaaaaa bbbbbbbbbbb ccccccccccccccc ddddddddddddd
always starts with "xyz_ 22". Check out here: (see comments also)
// prepared a string similar to what you already have
NSMutableString *xmlfile = [[NSMutableString alloc] initWithFormat:#"%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#",
#"asasasasasas",
#"wewewewewewe",
#"xyz_ 22 aaaaaaaaaaa bbbbbbbbbbb ccccccccccccccc ddddddddddddd",
#"fgfgfgfgfgfgfg",
#"ererererererer",
#"",
#"abc_ 12 bbbbbbbbbb dddddddd",
#"jkjkjkjkjkjkjk",
#"lalallalalalal"];
NSLog(#"%#", xmlfile); // check out by printing (optional)
NSArray *arr = [xmlfile componentsSeparatedByString:#"\n"]; // first break with NEWLINE character
NSLog(#"%#",arr); // check out by printing (optional)
for (NSString *str in arr) // traverse all lines
{
if([str hasPrefix:#"xyz_ 22"]) // if it starts with "xyz_ 22"
{
NSMutableArray *mArr = [[NSMutableArray alloc] initWithArray:[[str stringByReplacingOccurrencesOfString:#"xyz_ 22 " withString:#""] componentsSeparatedByString:#" "]];
for(int i=0; i< [mArr count];i++ )
{
NSString *tag;
if([[mArr objectAtIndex:i] length] > 3)
{
// If more than three i.e., aaaaa then write <aaa>aaaaaaa<aaa>
tag = [[mArr objectAtIndex:i] substringWithRange:NSMakeRange(0, 3)];
}
else
{
// If less than three i.e., aa then pick <aa>aa<aa> or
a then pick <a>a<a>
tag = [mArr objectAtIndex:i];
}
NSString *s= [[NSString alloc] initWithFormat:#"<%#>%#<%#>", tag, [mArr objectAtIndex:i], tag];
[mArr removeObjectAtIndex:i];
[mArr insertObject:s atIndex:i];
}
NSLog(#"%#", mArr); // prints output
}
}
If start of line do not fixed with "xyz_ 22", you need to have a look at NSRegularExpression class and use it instead of using hasPrefix.
This sample pattern can help you:
#"^(.{3}\_\s*\d{2}\s*)"
This pattern matches any line that has three characters followed by an underscore and space(s) followed by two digits followed by space(s).
You can use either of these functions then as per your need:
firstMatchInString:options:range:
matchesInString:options:range:
numberOfMatchesInString:options:range:
Hope it helps.
Happy coding and reading!!!
EDIT:
I have updated code but i have doubt on the no. of characters in a tag you specified in comment. well this will give you an idea on how to work around this issue.
String "test" is not present in the string to be formatted .Try to remove it and then try with [contentFile componentsSeparatedByString#" "]
If you want to break the string by new line, try this one :
NSArray *lineFile=[contentFile componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
instead of
NSArray *lineFile = [contentFile componentsSeparatedByString:#"\n"];

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

How to get integer values from nsstring Evalution in iPhone?

I have NSString like this #"0,0,0,0,0,0,1,2012-03-08,2012-03-17". I want values separated by comma. I want values before comma and neglect comma.
I am new in iPhone, I know how to do in Java but not getting how to do in Objective-C.
NSString *string = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *componentArray = [string componentSeperatedByString:#","];
Use the componentsSeparatedByString: method of NSString.
NSString *str = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *components = [str componentsSeparatedByString:#","];
for (NSString *comp in components)
{
NSLog(#"%#", comp);
}
for (NSString *s in [yourstring componentsSeparatedByString:#","])
{
int thisval = [s intValue];
}

how to remove particular words from strings?

I have an NSString *str, having value #"I like Programming and gaming."
I have to remove "I" "like" & "and" from my string so it should look like as "Programming gaming"
How can I do this, any Idea?
NSString *newString = #"I like Programming and gaming.";
NSString *newString1 = [newString stringByReplacingOccurrencesOfString:#"I" withString:#""];
NSString *newString12 = [newString1 stringByReplacingOccurrencesOfString:#"like" withString:#""];
NSString *final = [newString12 stringByReplacingOccurrencesOfString:#"and" withString:#""];
Assigned to wrong string variable edited now it is fine
NSLog(#"%#",final);
output : Programming gaming
NSString * newString = [#"I like Programming and gaming." stringByReplacingOccurrencesOfString:#"I" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"like" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"and" withString:#""];
NSLog(#"%#", newString);
More efficient and maintainable than doing a bunch of stringByReplacing... calls in series:
NSSet* badWords = [NSSet setWithObjects:#"I", #"like", #"and", nil];
NSString* str = #"I like Programming and gaming.";
NSString* result = nil;
NSArray* parts = [str componentsSeparatedByString:#" "];
for (NSString* part in parts) {
if (! [badWords containsObject: part]) {
if (! result) {
//initialize result
result = part;
}
else {
//append to the result
result = [NSString stringWithFormat:#"%# %#", result, part];
}
}
}
It is an old question, but I'd like to show my solution:
NSArray* badWords = #[#"the", #"in", #"and", #"&",#"by"];
NSMutableString* mString = [NSMutableString stringWithString:str];
for (NSString* string in badWords) {
mString = [[mString stringByReplacingOccurrencesOfString:string withString:#""] mutableCopy];
}
return [NSString stringWithString:mString];
Make a mutable copy of your string (or initialize it as NSMutableString) and then use replaceOccurrencesOfString:withString:options:range: to replace a given string with #"" (empty string).

Getting the wrong string from components separatedByString method

I am using the following code to get the title of a string. Everything works up to the line where I get return [s2 objectAtIndex:0]. The problem is that it is just removing the "&" from the string instead of getting the string in front of the "&". For example:
I am trying to get the title from the string "Sweat (David Guetta Remix) - Snoop Dogg & David Guetta". The method would return "Sweat David Guetta" rather than "Sweat". If you can see the problem please point it out, as it will be of much help!
- (NSString *)getTitleFromString:(NSString *)string {
NSString *newSongName = [NSString stringWithString:string];
NSArray *chunks = [newSongName componentsSeparatedByString:#"-"];
NSString *chunks2s = [chunks objectAtIndex:0];
NSArray *chunks2 = [chunks2s componentsSeparatedByString:#"("];
NSString *s = [chunks2 objectAtIndex:0];
NSArray *s2 = [s componentsSeparatedByString:#"&"];
return [s2 objectAtIndex:0];
}
Edit----- Finalized Code:
- (NSString *)getTitleFromString:(NSString *)string {
NSArray * a = [string componentsSeparatedByString:#"-"];
NSString *b = [a objectAtIndex:0];
NSArray *c = [b componentsSeparatedByString:#"("];
NSString *d = [c objectAtIndex:0];
NSArray *e = [d componentsSeparatedByString:#"&"];
if ([e count] > 2) {
return [e objectAtIndex:0];
}
else {
return d;
}
return #"";
}
Given the initial starting string "Sweat (David Guetta Remix) - Snoop Dogg & David Guetta":
chunks will be ["Sweat (David Guetta Remix) ", " Snoop Dogg & David Guetta"] (the string split at the "-")
chunks2s will be "Sweat (David Guetta Remix) " (the first element of chunks)
chunks2 will be "["Sweat ", "David Guetta Remix) "]" (that string split at the opening paren)
s will thus be "Sweat " (the first element of chunks2)
And s2 will be the same thing as s, so the method should be returning the correct thing. If it is not, then one of your assumptions is wrong.