删除 NSString 的一部分并将其复制到另一个 NSString

发布于 2024-12-02 04:33:11 字数 487 浏览 3 评论 0原文

所以我有一个 NSString,让我们这么说: NSString *mainString = @"My Name is Andrew (I likecomputer)"; 我想从 mainString 中删除从“(”到“)”的所有内容。我想将“()”之间的所有内容放入子字符串中。

例如:

NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;

//The code I need help with

mainString = @"y Name is Andrew ";
subString = @"I like computers";

我希望这是有道理的。这真的会对我有帮助。提前致谢。我一直在使用 NSRangeNSMutableStrings 但遇到了麻烦。提前致谢。

So I have an NSString, lets say it: NSString *mainString = @"My Name is Andrew (I like computers)";
And I want remove everything from the "(" to the ")" from mainString. And I want to put everything in between the "()" into a subString.

For example:

NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;

//The code I need help with

mainString = @"y Name is Andrew ";
subString = @"I like computers";

I hope this makes sense. It would really help me. Thanks in Advance. I've been playing with NSRange and NSMutableStrings but I'm having trouble. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蹲墙角沉默 2024-12-09 04:33:11
int startPosition = [mainString rangeOfString:@"("].location + 1;
int endPosition   = [mainString rangeOfString:@")"].location;

NSRange range = NSMakeRange(startPosition, endPosition - startPosition);

NSString *subString = [mainString substringWithRange:range];

正如 darvids0n 在下面的评论中提到的:

    mainString = [mainString substringToIndex:startPosition - 1]
int startPosition = [mainString rangeOfString:@"("].location + 1;
int endPosition   = [mainString rangeOfString:@")"].location;

NSRange range = NSMakeRange(startPosition, endPosition - startPosition);

NSString *subString = [mainString substringWithRange:range];

and as darvids0n has mentioned in below comment:

    mainString = [mainString substringToIndex:startPosition - 1]
寒尘 2024-12-09 04:33:11

这可能是一个更简单的方法:

NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;

NSArray *array = [mainString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"()"]];

mainString = [array objectAtIndex:0]; // "My Name is Andrew "
subString = [array objectAtIndex:1]; // "I like computers"

This is probably an easier way:

NSString *mainString = @"My Name is Andrew (I like computers)";
NSString *subString;

NSArray *array = [mainString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"()"]];

mainString = [array objectAtIndex:0]; // "My Name is Andrew "
subString = [array objectAtIndex:1]; // "I like computers"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文