Как проверить на строку
Перейти к содержимому

Как проверить на строку

  • автор:

String. Is Null OrEmpty(String) Метод

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Указывает, действительно ли указанная строка является строкой null или пустой строкой («»).

public: static bool IsNullOrEmpty(System::String ^ value);
public static bool IsNullOrEmpty (string value);
public static bool IsNullOrEmpty (string? value);
static member IsNullOrEmpty : string -> bool
Public Shared Function IsNullOrEmpty (value As String) As Boolean
Параметры

Строка для проверки.

Возвращаемое значение

Значение true , если параметр value равен null или пустой строке («»); в противном случае — значение false .

Примеры

В следующем примере рассматриваются три строки и определяется, имеет ли каждая строка значение, является ли пустой строкой или имеет значение null .

using namespace System; String^ Test( String^ s ) < if (String::IsNullOrEmpty(s)) return "is null or empty"; else return String::Format( "(\"\") is neither null nor empty", s ); > int main() < String^ s1 = "abcd"; String^ s2 = ""; String^ s3 = nullptr; Console::WriteLine( "String s1 .", Test( s1 ) ); Console::WriteLine( "String s2 .", Test( s2 ) ); Console::WriteLine( "String s3 .", Test( s3 ) ); > // The example displays the following output: // String s1 ("abcd") is neither null nor empty. // String s2 is null or empty. // String s3 is null or empty. 
string s1 = "abcd"; string s2 = ""; string s3 = null; Console.WriteLine("String s1 .", Test(s1)); Console.WriteLine("String s2 .", Test(s2)); Console.WriteLine("String s3 .", Test(s3)); String Test(string s) < if (String.IsNullOrEmpty(s)) return "is null or empty"; else return String.Format("(\"\") is neither null nor empty", s); > // The example displays the following output: // String s1 ("abcd") is neither null nor empty. // String s2 is null or empty. // String s3 is null or empty. 
Class Sample Public Shared Sub Main() Dim s1 As String = "abcd" Dim s2 As String = "" Dim s3 As String = Nothing Console.WriteLine("String s1 .", Test(s1)) Console.WriteLine("String s2 .", Test(s2)) Console.WriteLine("String s3 .", Test(s3)) End Sub Public Shared Function Test(s As String) As String If String.IsNullOrEmpty(s) Then Return "is null or empty" Else Return String.Format("("""") is neither null nor empty", s) End If End Function End Class ' The example displays the following output: ' String s1 ("abcd") is neither null nor empty. ' String s2 is null or empty. ' String s3 is null or empty. 
let test (s: string): string = if String.IsNullOrEmpty(s) then "is null or empty" else $"(\"\") is neither null nor empty" let s1 = "abcd" let s2 = "" let s3 = null printfn "String s1 %s" (test s1) printfn "String s2 %s" (test s2) printfn "String s2 %s" (test s3) // The example displays the following output: // String s1 ("abcd") is neither null nor empty. // String s2 is null or empty. // String s3 is null or empty. 

Комментарии

IsNullOrEmpty — это удобный метод, позволяющий одновременно проверить, является ли String объект или null его значение равно String.Empty. Это эквивалентно следующему коду:

result = s == nullptr || s == String::Empty; 
bool TestForNullOrEmpty(string s) < bool result; result = s == null || s == string.Empty; return result; >string s1 = null; string s2 = ""; Console.WriteLine(TestForNullOrEmpty(s1)); Console.WriteLine(TestForNullOrEmpty(s2)); // The example displays the following output: // True // True 
result = s Is Nothing OrElse s = String.Empty 
let testForNullOrEmpty (s: string): bool = s = null || s = String.Empty let s1 = null let s2 = "" printfn "%b" (testForNullOrEmpty s1) printfn "%b" (testForNullOrEmpty s2) // The example displays the following output: // true // true 

Метод можно использовать для IsNullOrWhiteSpace проверки того, является null ли строка , ее значение равно String.Emptyили она состоит только из пробелов.

Что такое строка null?

Строка имеет значение , null если ей не было присвоено значение (в C++ и Visual Basic) или если ей явно присвоено значение null . Хотя функция составного форматирования может корректно обрабатывать строку null, как показано в следующем примере, при попытке вызвать ее, если ее члены вызывают .NullReferenceException

using namespace System; void main() < String^ s; Console::WriteLine("The value of the string is ''", s); try < Console::WriteLine("String length is ", s->Length); > catch (NullReferenceException^ e) < Console::WriteLine(e->Message); > > // The example displays the following output: // The value of the string is '' // Object reference not set to an instance of an object. 
 String s = null; Console.WriteLine("The value of the string is ''", s); try < Console.WriteLine("String length is ", s.Length); > catch (NullReferenceException e) < Console.WriteLine(e.Message); >// The example displays the following output: // The value of the string is '' // Object reference not set to an instance of an object. 
Module Example Public Sub Main() Dim s As String Console.WriteLine("The value of the string is ''", s) Try Console.WriteLine("String length is ", s.Length) Catch e As NullReferenceException Console.WriteLine(e.Message) End Try End Sub End Module ' The example displays the following output: ' The value of the string is '' ' Object reference not set to an instance of an object. 
let (s: string) = null printfn "The value of the string is '%s'" s try printfn "String length is %d" s.Length with | :? NullReferenceException as ex -> printfn "%s" ex.Message // The example displays the following output: // The value of the string is '' // Object reference not set to an instance of an object. 

Что такое пустая строка?

Строка пуста, если ей явно назначена пустая строка («») или String.Empty. Пустая строка имеет значение Length 0. В следующем примере создается пустая строка и отображается ее значение и длина.

String^ s = ""; Console::WriteLine("The length of '' is .", s, s->Length); // The example displays the following output: // The length of '' is 0. 
String s = ""; Console.WriteLine("The length of '' is .", s, s.Length); // The example displays the following output: // The length of '' is 0. 
Dim s As String = "" Console.WriteLine("The length of '' is .", s, s.Length) ' The example displays the following output: ' The length of '' is 0. 
let s = "" printfn "The length of '%s' is %d." s s.Length // The example displays the following output: // The length of '' is 0. 

Как проверить содержит ли строка подстроку java

Для того, чтобы найти подстроку в строке в Java , вы можете использовать метод indexOf() или lastIndexOf() класса String . Эти методы позволяют найти индекс первого (или последнего) вхождения заданной подстроки в строке. Если подстрока не найдена, методы возвращают -1.

Например, чтобы найти индекс первого вхождения подстроки «world» в строке «Hello world!», вы можете использовать следующий код:

String str = "Hello world!"; int index = str.indexOf("world"); System.out.println(index); // => 6 

Также можно использовать метод contains() для проверки наличия подстроки в строке без необходимости получать ее индекс.

String str = "Hello world!"; boolean contains = str.contains("world"); System.out.println(contains); // => true 

Как проверить переменную на тип str в Python 3?

Привет всем. В процессе написания программы на Python 3 потребовалось проверить переменную на тип str (то есть узнать, принадлежит ли переменная типу string ) Пробовал конструкцию try — except , но в данном случае ошибки не происходит, не смотря на то, что переменная может являтся любого типа (ну или почти любого). Пробовал также вот такое условие:

if type(*имя переменной*) != : : 

Но из этого тоже ничего не выходит. Выдает ошибку:

if type(*имя переменной*) != : ^ SyntaxError: invalid syntax 
  1. В чем ошибка и можно ли её устранить?
  2. Если нет, то какие существуют способы решения задачи?
  3. Можно ли осуществлять такую проверку на другие типы переменных?

P.S. Заранее извиняюсь, если этот вопрос дубликат. В таком случаее попрощу дать ссылки на ответы, сам вопрос могу удалить (если ответы решат мою проблему)

String.prototype.includes()

Метод includes() проверяет, содержит ли строка заданную подстроку, и возвращает, соответственно true или false .

Синтаксис

str.includes(searchString[, position])

Параметры

Строка для поиска в данной строке.

Позиция в строке, с которой начинать поиск строки searchString , по умолчанию 0.

Возвращаемое значение

true , если искомая строка была найдена в данной строке; иначе false .

Описание

Этот метод позволяет вам определять, содержит ли строка другую строку.

Чувствительность к регистру символов

Метод includes() является регистрозависимым. Например, следующее выражение вернёт false :

"Синий кит".includes("синий"); // вернёт false 

Примеры

Использование includes()

var str = "Быть или не быть вот в чём вопрос."; console.log(str.includes("Быть")); // true console.log(str.includes("вопрос")); // true console.log(str.includes("несуществующий")); // false console.log(str.includes("Быть", 1)); // false console.log(str.includes("БЫТЬ")); // false 

Полифил

Этот метод был добавлен в спецификации ECMAScript 2015 и может быть недоступен в некоторых реализациях JavaScript. Однако, можно легко эмулировать этот метод:

if (!String.prototype.includes)  String.prototype.includes = function (search, start)  "use strict"; if (typeof start !== "number")  start = 0; > if (start + search.length > this.length)  return false; > else  return this.indexOf(search, start) !== -1; > >; > 

Спецификации

Specification
ECMAScript Language Specification
# sec-string.prototype.includes

Совместимость с браузерами

BCD tables only load in the browser

String.prototype.contains

В Firefox с версии 18 по версию 39, этот метод назывался «contains». Он был переименован в «includes» в замечании Firefox bug 1102219 по следующей причине:

Как было сообщено, некоторые сайты, использующие MooTools 1.2, ломаются в Firefox 17. Эта версия MooTools проверяет существование метода String.prototype.contains() и, если он не существует, добавляет свой собственный. С введением этого метода в Firefox 17, поведение этой проверки изменилось таким образом, что реализация String.prototype.contains() , основанная на MooTools, сломалась. В результате это изменение было отключено в Firefox 17. Метод String.prototype.contains() доступен в следующей версии Firefox — Firefox 18.

MooTools 1.3 принудительно использует свою собственную версию метода String.prototype.contains() , так что использующие его веб-сайты не должны ломаться. Тем не менее, следует отметить, что сигнатура метода в MooTools 1.3 отличается от сигнатуры метода в ECMAScript 2015 (во втором аргументе). В MooTools 1.5+ сигнатура изменена для соответствия стандарту ES2015.

В Firefox 48, метод String.prototype.contains() был удалён. Следует использовать только String.prototype.includes() .

Смотрите также

  • Array.prototype.includes() Экспериментальная возможность
  • TypedArray.prototype.includes() (en-US) Экспериментальная возможность
  • String.prototype.indexOf()
  • String.prototype.lastIndexOf()
  • String.prototype.startsWith()
  • String.prototype.endsWith()

Found a content problem with this page?

  • Edit the page on GitHub.
  • Report the content issue.
  • View the source on GitHub.

This page was last modified on 6 янв. 2024 г. by MDN contributors.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *