简体   繁体   English

如何在不插入空格的情况下替换NSString中的字符?

[英]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. 我得到2010-04-05 18:51:18.885 TestString[6823:a0f] Helloxx作为输出。 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. 这将确保字符串中只有5个字符,但要注意,如果字符串中至少有 5个字符开头,这也会引发异常。 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 另一种方式你可以使用.. 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 "*" “token”是你想要替换NSString而“i”是你想要用“*”来改变NSString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM