objective-c 如何从 NSString 中删除前 3 个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1073872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:51:20  来源:igfitidea点击:

How to remove first 3 characters from NSString?

objective-cnsstring

提问by Rahul Vyas

I have a string like this "A. rahul VyAs"

我有一个像这样的字符串“A. rahul VyAs”

and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"

我想删除“A.”和“A”后面的空格。所以新字符串将是“rahul VyAs”

How do i achieve this?

我如何实现这一目标?

回答by Alex Rozanski

You can use the NSStringinstance methods substringWithRange:or substringFromIndex:

您可以使用NSString实例方法substringWithRange:substringFromIndex:

NSString *str = @"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];

or

或者

NSString *str = @"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];

回答by rakeshNS

Try this,

尝试这个,

char *string=[@"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];

回答by App Dev Guy

This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?

这是我看到的一个解决方案,专门用于删除经常出现的前缀并解决问题的答案如何删除“A.”?

NSString * name =  @"A. rahul VyAs";
NSString * prefixToRemove = @"A. "; 
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];

This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.

如果字符集存在,此代码将删除您告诉它删除/更改的内容,例如 "A.",即使三个字符(或更多/更少)位于字符串的中间。

If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.

如果你想删除rahul,你可以。它的多样性在于您准确指定要删除或更改的内容,如果它存在于 String 中的任何位置,它将被删除或更改。

If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.

如果您只想从文本前面删除特定数量的字符,这些字符总是随机的或未知的,请使用 [string length] 方法作为最佳答案。

If you want to remove or changecertain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.

如果您想删除或更改某些重复出现的字符,我使用的方法将启用它,类似于文档编辑器上的 Wordsearch。

回答by Alex Zavatone

It's this simple:

就这么简单:

myString = [myString subStringFromIndex:3]

That's it.

就是这样。