Как вывести пустую строку?
Если вписать в терминал node file.js <пустая строка>(т.е. ничего не вписать) выдаст ошибку:
пустая>
for(let l=str_min.length; l>0; l--)< ^ TypeError: Cannot read property 'length' of undefined
Как сделать так, чтобы если ничего не вписывать, просто выдавало пустую строку?
function search_largest_substr() < let str_min = arguments[0]; const list = []; for(let n=1; nlist.push(str_min); str_min = arguments[n]; > for(let l=str_min.length; l>0; l--)< for(let p=0; p= 0) continue; isFound=false; break; > if( isFound ) return substr; > > return ""; > console.log(search_largest_substr.apply(this,process.argv.slice(2)));
- Вопрос задан более двух лет назад
- 975 просмотров
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.
Как напечатать пустую строку в c++?
В питоне я пишу просто print()
А как тоже самое написать в c++
Я пробовал (естественно внутри main):
std::cout Ошибка вышла.
Ещё пробовал:
std::cout И опять ошибка. И еще пробовал:
std::endl;
И опять ошибка
- Вопрос задан более трёх лет назад
- 1918 просмотров
2 комментария
Простой 2 комментария
Евгений Шатунов @MarkusD Куратор тега C++
Maxim Siomin , а какие у тебя ошибки вышли, это, конечно же, секретный секрет? Делиться не будешь?
Литерал пустой строки - это "" . Лично я не вижу проблемы его вывести.
Или тебе нужно не пустую строку вывести, а перевести каретку на следующую строку?
Как вывести пустую строку
Для отключения данного рекламного блока вам необходимо зарегистрироваться или войти с учетной записью социальной сети.
Железных Дел Мастер
Сообщения: 24413
Благодарности: 4461
| Конфигурация компьютера | |
| Процессор: Ryzen R5 3600 @ 4,2GHz w Zalman CNPS 10x Performa | |
| Материнская плата: Asrock (AB350 Pro4) | |
| Память: 16Gb Crucial (2 x 8Gb DDR4-3000 Ballistix Sport LT Grey (BLS8G4D30AESBK)) @3533MHz (16-18-16-30) & 1.37V | |
| HDD: Samsung SSD 860 Evo 250Gb M.2 (MZ-N6E250BW); WD HDD 1Tb (WD10EARS-00Y5B1); TOSHIBA 2Tb (MK2002TSKB); Samsung Portable 500GB (MU-PA500B/WW) | |
| Видеокарта: 12Gb Palit RTX 3060 (NE63060T19K9-190AD) | |
| Блок питания: Seasonic 620W M12II-620 Evo Bronze (SS-620GM2) | |
| CD/DVD: LG (HL-DT-ST BDDVDRW CH10LS20) | |
| Монитор: Dell 24" (2408WFP) | |
| Ноутбук/нетбук: Asus E402M | |
| ОС: Win10 x64 Pro | |
| Прочее: APC Back-UPS RS 1000 || Logitech MK270|| Logitech c310|| Mikrotik 952Ui-5ac2nD || Creative Inspire 5.1 Digitall 5700 || LG 47LM580T |
DedAlex, спасибо, брат. Чесслово не знал - уже и кодом заменял (Alt+255, в DOSе прокатывало) и.. чего только не делал. В обсчем, век живи, век.. - учись)))
ЗЫ: где нашел инфу-то? Нет там, часом, "echo+" или "echo*"
Последний раз редактировалось ShaddyR, 25-04-2008 в 15:44 .