Ranjeet Sajwan
Ranjeet Sajwan

Reputation: 1921

replace characters in a string

i have a sting in which i want to replace all characters(except special characters) by X.. i mean if i have a string str= mac,iphone & ipad are products of apple

theis should be converted to

str= XXX,XXXXXX & XXXX XXX XXXXXXXX XX XXXXX

i know this can be done by finding all special characters and note their position and then replace all other characters except these special characters but there are so many special characters should i check them one by one ? or is there any other method to identify them

please help

Upvotes: 0

Views: 1992

Answers (5)

Sabby
Sabby

Reputation: 2592

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if(TextFound)
    {
        NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/<br />"];
        string = [[string componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];

        TextStr = [TextStr stringByAppendingString:string];
    }
}

As I did it in my parsing, it was showing linebreak character in the text. I tried the way stringbyrplacingoccurance of string, but nothing happened, so finally it worked.

Upvotes: 1

Sabby
Sabby

Reputation: 2592

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); 

Try this. It is more useful when the above answered ways don't replace the characters.

Upvotes: 2

Swastik
Swastik

Reputation: 2425

NSString *str=@"mac,iphone & ipad";

for(int i=0;i<[str length];i++)
{
    int str1=(int)[str characterAtIndex:i];
    NSString *temp=[NSString stringWithFormat:@"%C",str1];

    if(str1 >96 && str1 <123  || str1 >64 && str1 <91)

        str = [str stringByReplacingOccurrencesOfString:temp withString:@"X"];
}

Hope this helps...This will replace all characters either in upper/lower case

Upvotes: 5

Nimrod
Nimrod

Reputation: 5133

I'd use a regular expression. Check out the documentation for NSRegularExpression

Upvotes: 0

GhostRider
GhostRider

Reputation: 1207

[Nsstring stringByReplacingOccurrencesOfString:@"" withString:@"X"];

from this you can replace string according to my knowledge

Upvotes: 1

Related Questions