Accessing Individual Characters

Individual characters contained in a string can be accessed using methods such as Substring, Replace, Split and Trim.

string s3 = "Visual C# Express";   System.Console.WriteLine(s3.Substring(7, 2)); // outputs "C#" System.Console.WriteLine(s3.Replace("C#", "Basic")); // outputs "Visual Basic Express"

It is also possible to copy the characters into a character array, like this:

string s4 = "Hello, World"; char[] arr = s4.ToCharArray(0, s4.Length);   foreach (char c in arr) { System.Console.Write(c); // outputs "Hello, World" }

Individual characters from a string can be accessed with an index, like this:

string s5 = "Printing backwards";   for (int i = 0; i < s5.Length; i++) { System.Console.Write(s5[s5.Length - i - 1]); // outputs "sdrawkcab gnitnirP" }

Доступ к отдельным знакам

К отдельным знакам, содержащимся в строке, можно получить доступ с помощью таких методов как Substring, Replace, Split и Trim.

 

string s3 = "Visual C# Express";

System.Console.WriteLine(s3.Substring(7, 2));

// Output: "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic"));

// Output: "Visual Basic Express"

 

 

Также можно скопировать знаки в массив знаков, как показано в следующем примере.

string s4 = "Hello, World";

char[] arr = s4.ToCharArray(0, s4.Length);

 

foreach (char c in arr)

{

System.Console.Write(c); // outputs "Hello, World"

}

Доступ к отдельным знакам в строке возможен с помощью индекса, как показано в следующем примере.

 

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)

{

System.Console.Write(s5[s5.Length - i - 1]);

}

// Output: "sdrawkcab gnitnirP"


Changing Case

To change the letters in a string to upper or lower case, use ToUpper() or ToLower(), like this:

string s6 = "Battle of Hastings, 1066";   System.Console.WriteLine(s6.ToUpper()); // outputs "BATTLE OF HASTINGS 1066" System.Console.WriteLine(s6.ToLower()); // outputs "battle of hastings 1066"

Смена регистра

Чтобы изменить регистр букв в строке (сделать их заглавными или строчными) следует использовать ToUpper() или ToLower(), как показано в следующем примере.

string s6 = "Battle of Hastings, 1066";

 

System.Console.WriteLine(s6.ToUpper());

// outputs "BATTLE OF HASTINGS 1066"

System.Console.WriteLine(s6.ToLower());

// outputs "battle of hastings 1066"


Comparisons

The simplest way to compare two strings is to use the == and != symbols, which perform a case-sensitive comparison.

string color1 = "red"; string color2 = "green"; string color3 = "red";   if (color1 == color3) { System.Console.WriteLine("Equal"); } if (color1 != color2) { System.Console.WriteLine("Not equal"); }

Сравнения

Наилучшим способом сравнения двух строк является использование операторов == и !=, которые обеспечивают сравнение с учетом регистра.

 

string color1 = "red";

string color2 = "green";

string color3 = "red";

 

if (color1 == color3)

{

System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

System.Console.WriteLine("Not equal");

}

String objects also have a CompareTo() method that returns an integer value based on whether one string is less-than (<) or greater-than (>) another. When comparing strings, the Unicode value is used, and lower case has a smaller value than upper case.

// Enter different values for string1 and string2 to

// experiment with behavior of CompareTo

string string1 = "ABC";

string string2 = "abc";

 

int result = string1.CompareTo(string2);

 

if (result > 0)

{

System.Console.WriteLine("{0} is greater than {1}", string1, string2);

}

else if (result == 0)

{

System.Console.WriteLine("{0} is equal to {1}", string1, string2);

}

else if (result < 0)

{

System.Console.WriteLine("{0} is less than {1}", string1, string2);

}//

Outputs: ABC is less than abc

Для строковых объектов также существует метод CompareTo(), возвращающий целочисленное значение, которое зависит от того, что одна строка может быть меньше (<) или больше (>) другой. При сравнении строк используется значение Юникода, при этом значение строчных букв меньше, чем значение заглавных.

// Enter different values for string1 and string2 to

// experiment with behavior of CompareTo

string string1 = "ABC";

string string2 = "abc";

 

int result2 = string1.CompareTo(string2);

 

if (result2 > 0)

{

System.Console.WriteLine("{0} is greater than {1}", string1, string2);

}

else if (result2 == 0)

{

System.Console.WriteLine("{0} is equal to {1}", string1, string2);

}

else if (result2 < 0)

{

System.Console.WriteLine("{0} is less than {1}", string1, string2);

}

// Output: ABC is less than abc[46]


To search for a string inside another string, use IndexOf(). IndexOf() returns -1 if the search string is not found; otherwise, it returns the zero-based index of the first location at which it occurs.

string s9 = "Battle of Hastings, 1066"; System.Console.WriteLine(s9.IndexOf("Hastings")); // outputs 10 System.Console.WriteLine(s9.IndexOf("1967")); // outputs -1

Чтобы найти строку внутри другой строки следует использовать IndexOf(). IndexOf() возвращает значение -1, если искомая строка не найдена; в противном случае возвращается индекс первого вхождения искомой строки (отсчет ведется с нуля).

string s9 = "Battle of Hastings, 1066";

System.Console.WriteLine(s9.IndexOf("Hastings")); // outputs 10

System.Console.WriteLine(s9.IndexOf("1967")); // outputs -1




Дата добавления: 2022-05-27; просмотров: 211;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, добавьте сайт познайка в закладки и расскажите о нем друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2026 год. Материал предоставляется для ознакомительных и учебных целей. Политика конфиденциальности
Генерация страницы за: 0.014 сек.