I am trying to filter words using this code
-(BOOL)isBadWord:(NSString*)string{
NSString* path = [[NSBundle mainBundle] pathForResource:#"wordlist"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *delimiter = #"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = #" ";
NSArray *searchItems = [string componentsSeparatedByString:character];
BOOL isContain = false;
for (int i = 0; i < searchItems.count; i++) {
if (![[searchItems objectAtIndex:i] isEqual:#""]) {
NSUInteger indexOfTheObject =[items containsObject:[searchItems objectAtIndex:i]];
if (indexOfTheObject > 0) {
isContain = true;
}
}
}
return isContain;
}
This is ok for single words, but if combination of words in the text file it not works. eg:
string = word1 {space} word2
What you basically need to do is to iterate an array of bad words/combinations and for each of these steps you should search for this combination on your string like this:
BOOL isContain = NO;
for (NSString *badWord in items) {
if ([string rangeOfString:badWord].location != NSNotFound) {
isContain = YES;
break;
}
}
return isContain;
Please note that BOOL can be YES and NO, but not true and false — it is a special scalar type you should use in Objectve-C when working with Cocoa/CocoaTouch.
Cheers! :)
P.S. it seems you do a lot of work with strings, it may be useful for you to see this String Programming Guide's chapter by Apple.
Related
I am trying to write a function which will allow me to determine whether one NSString* contains the characters of another NSString*. As an example, refer to the below scenario:
NSString *s1 = #"going";
NSString *s2 = #"ievngcogdl";
So essentially when the comparison between these 2 strings occurs, it should return true as the first string s1 has the same characters of the second string s2. Could I use an NSCountedSet? I know that this class has a method containsObject:(id) although I don't think that will solve my problem. Is there any other ways in completing this function and provide me the required results?
I think this method could be rather slow, but I would still favour it over [NSString rangeOfCharacterFromSet:], which requires creating an NSCharacterSet object per comparison:
- (BOOL)string:(NSString *)string containsAllCharactersInString:(NSString *)charString {
NSUInteger stringLen = [string length];
NSUInteger charStringLen = [charString length];
for (NSUInteger i = 0; i < charStringLen; i++) {
unichar c = [charString characterAtIndex:i];
BOOL found = NO;
for (NSUInteger j = 0; j < stringLen && !found; j++)
found = [string characterAtIndex:j] == c;
if (!found)
return NO;
}
return YES;
}
This will work -
-(BOOL) string:(NSString *)string1 containsInputString:(NSString *)string2 {
// Build a set of characters in the string
NSCountedSet *string1Set = [[NSCountedSet alloc]init];
[string1 enumerateSubstringsInRange:NSMakeRange(0, string1.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[string1Set addObject:substring];
}];
// Now iterated over string 2, removing characters from the counted set as we go
for (int i=0;i<string2.length;i++) {
NSRange range = [string2 rangeOfComposedCharacterSequenceAtIndex:i];
NSString *substring = [string2 substringWithRange:range];
if ([string1Set countForObject:substring]> 0) {
[string1Set removeObject:substring];
}
else {
return NO;
}
}
return YES;
}
Regular Expressions are the best way to check this type of conditions and check this link once
Below I am adding the code for your solution, please check once
NSString *s1 = #"going"
NSString *s2 = #"ievngcogdl";
if ([self string:s1 containsSameCharacterofString:s2]) {
NSLog(#"YES");
}
- (BOOL)string:(NSString *)str containsSameCharacterofString:(NSString *)charString
{
if (charString.length >= str.length) {
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:#"^[%#]+$", charString] options:NSRegularExpressionCaseInsensitive error:&error];
NSRange textRange = NSMakeRange(0, str.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:str options:NSMatchingReportProgress range:textRange];
return (matchRange.location != NSNotFound);
}
else {
return NO;
}
}
BOOL containsString = [#"Hello" containsString:#"llo"];
if (containsString) {
// Do Stuff
}
Am having this nsstring
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
now i want to display only the countries which are suffixed by "en_US".
can anybody tell me how to split that string to get the countries.
I did like this
NSError * error;
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"CountryList" ofType:#"txt"];
NSString * countrStr = [NSString stringWithContentsOfFile:imageName encoding:NSStringEncodingConversionAllowLossy error:&error];
NSArray * dfd = [countrStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<dfd.count;i++)
{
NSString * nama = [dfd objectAtIndex:1];
NSArray * djk = [nama componentsSeparatedByString:#","];
NSString * aksjd = [djk objectAtIndex:1];
}
You can do it like this;
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
NSArray * arrData = [countryStr componentsSeparatedByString:#","];;//[countryStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<arrData.count;i++)
{
NSString * str = [arrData objectAtIndex:i];
if ([str isEqualToString:#"en_US"] && i<arrData.count-1)
{
NSString* countryName = [arrData objectAtIndex:i+1];
NSLog(#"countryName %#", countryName);
}
}
But you should manage data in your file, loading from resource.
Best way to do it is
NSString *string = [NSString stringWithFormat: #"%#, %#, %#", var1, var2, var3];
Excuse the formatting/syntax errors. Typing this via iPhone. But if there is any errors, look up stringWithFormat: in iOS documents on the apple developer page for corrections.
Your string seems to have the following pattern:
A number,
An other number,
The country language code,
The name,
A short code,
An (other) name.
So what you can do is to use a loop like this:
for (int i = 0; i < dfd.count; i += 6) {
if ( dfd[i + 2] ) } // check the country code at index i + 2
// Do something
}
}
split the sentence into words with out using "componentsSeparatedByString:"
my word is "This is a well known simple"
I wrote like this separtedWord=[noteTextView.text componentsSeparatedByString: #" "];
but I want with out using componentsSeparatedByString.please help me
I have wrote following logic. Created two properties like this :
#property(nonatomic,strong) NSMutableArray *strings;
#property(nonatomic,strong) NSMutableString *tempString;
Wrote business logic like this :
NSString *sampleString = #"This is a well known simple";
self.tempString = [[NSMutableString alloc] init];
self.strings = [[NSMutableArray alloc] init];
for( int i = 0; i < sampleString.length; i++ )
{
unichar currentChar = [sampleString characterAtIndex:i];
NSString *character = [NSString stringWithCharacters:¤tChar length:1];
if( currentChar != ' ' )
{
[self.tempString appendString:character];
if( i == sampleString.length - 1 )
{
[self addString:self.tempString];
}
}
else
{
[self addString:self.tempString];
[self.tempString setString:#""];
}
}
NSLog(#"Array Of String = %#",self.strings);
- (void)addString:(NSString *)string
{
[self.strings addObject:[NSString stringWithString:string]];
}
2014-07-24 15:23:22.306 ViemoPlayer[1834:70b] Array Of String = (
This,
is,
a,
well,
known,
simple
)
Hope this helps.
Convert the NSString into a char array.
Loop through the array and an if statement inside, and keep appending the charecters inside the charArray into a local NSMutableString using
for(int i =0;i<[myCharArray count];i++){
NSMutableString *teststring;
[teststring appendString:[myCharArray objectAtIndex : i]];
if([myCharArray objectAtIndex] == " "){
NSLog(teststring);
teststring = #""; //emptying the testString when we get a space
}
}
That should do it
I have a name textfield in my app, where both the firstname maybe a middle and a lastname is written. Now I want to split these components by the first whitespace, the space between the firstname and the middlename/lastname, so I can put it into my model.
For example:
Textfield Text: John D. Sowers
String 1: John
String 2: D. Sowers.
I have tried using [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject]; & [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lastObject];
But these only work if have a name without a middlename. Since it gets the first and the last object, and the middlename is ignored.
So how would I manage to accomplish what I want?
/*fullNameString is an NSString*/
NSRange rangeOfSpace = [fullNameString rangeOfString:#" "];
NSString *first = rangeOfSpace.location == NSNotFound ? fullNameString : [fullNameString substringToIndex:rangeOfSpace.location];
NSString *last = rangeOfSpace.location == NSNotFound ? nil :[fullNameString substringFromIndex:rangeOfSpace.location + 1];
...the conditional assignment (rangeOfSpace.location == NSNotFound ? <<default value>> : <<real first/last name>>) protects against an index out of bounds error.
Well that method is giving you an array with all the words split by white space, so then you can grab the first object as the first name and the rest of the objects as middle/last/etc
NSArray *ar = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstName = [ar firstObject];
NSMutableString *rest = [[NSMutableString alloc] init];
for(int i = 1; i < ar.count; i++)
{
[rest appendString:[ar objectAtIndex:i]];
[rest appendString:#" "];
}
//now first name has the first name
//rest has the rest
There might be easier way to do this, but this is one way..
Hope it helps
Daniel
I think this example below I did, solves your problem.
Remember you can assign values from the array directly, without transforming into string.
Here is an example:
NSString *textField = #"John D. Sowers";
NSArray *fullName = [textField componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" "]];
if (fullName.count)
{
if (fullName.count > 2)
{
NSLog(#"Array has more than 2 objects");
NSString *name = fullName[0];
NSLog(#"Name:%#",name);
NSString *middleName = fullName[1];
NSLog(#"Middle Name:%#",middleName);
NSString *lastName = fullName[2];
NSLog(#"Last Name:%#",lastName);
}
else if(fullName.count == 2)
{
NSLog(#"Array has 2 objects");
NSString *name = fullName[0];
NSLog(#"Name:%#",name);
NSString *lastName = fullName[1];
NSLog(#"Last Name:%#",lastName);
}
else
{
NSString *name = fullName[0];
}
}
I found this to be most robust:
NSString *fullNameString = #"\n Barnaby Marmaduke \n \n Aloysius ";
NSMutableArray *nameArray = [[fullNameString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
[nameArray removeObject:#""];
NSString *firstName = [nameArray firstObject];
if(nameArray.count)
{
[nameArray removeObjectAtIndex:0];
}
NSString *nameRemainder = [nameArray componentsJoinedByString:#" "];
Bob's your uncle.
So my textfield has the following text. #"A big Tomato is red."
I want to get the word before "is".
When I type
NSString *someString = [[textfield componentsSeparatedByString:#"is"]objectAtIndex:0];
I always get "A big Tomato" instead of just "Tomato". In the app people will type things before "is" so I need to always get the string before "is". I would appreciate any help I can get. *Warning,
This is a very difficult problem.
Try this,
NSString *value = #"A big Tomato is red.";
NSArray *array = [value componentsSeparatedByString:#" "];
if ([array containsObject:#"is"]) {
NSInteger index = [array indexOfObject:#"is"];
if (index != 0) {
NSString *word = [array objectAtIndex:index - 1];
NSLog(#"%#", word);
}
}
Try this
NSString *string = #"A big Tomato is red.";
if ([string rangeOfString:#"is"].location == NSNotFound) {
NSLog(#"string does not contain is");
} else {
NSLog(#"string contains is!");
}
try this
NSString *str = #"A big tomato is red";
NSArray *arr = [str componentsSeparatedByString:#" "];
int index = [arr indexOfObject:#"is"];
if(index > 1)
NSString *str_tomato = arr[index-1];
else
//"is" is the first word of sentence
as per yvesleborg's comment