如何检查字符串是否包含空格

发布于 2024-12-19 16:09:35 字数 25 浏览 2 评论 0原文

如何检查字符串字符之间是否包含空格?

How to check whether a string contains whitespaces in between characters?

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

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

发布评论

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

评论(2

心头的小情儿 2024-12-26 16:09:35

使用 rangeOfCharactersFromSet:

NSString *foo = @"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
    NSLog(@"Found whitespace");
}

注意:这也会在字符串的开头或结尾查找空格。如果你不想先修剪字符串......

NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];

use rangeOfCharactersFromSet:

NSString *foo = @"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
    NSLog(@"Found whitespace");
}

note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...

NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
走野 2024-12-26 16:09:35

您还可以按照以下步骤操作:

NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];

如果字符串中存在空格,那么它将分隔这些空格并将不同的组件存储在数组中。现在您需要计算数组的计数。如果count大于1,则意味着有两个组成部分,即存在空白。

if([componentsSeparatedByWhiteSpace count] > 1){
    NSLog(@"Found whitespace");
}

You can also follow these steps:

NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];

If there is any whitespace in your string, then it will separate those and store different components in the array. Now you need to take the count of array. If count is greater than 1, it means there are two components, i.e, presence of white space.

if([componentsSeparatedByWhiteSpace count] > 1){
    NSLog(@"Found whitespace");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文