Accessing Individual Characters
Individual characters that are contained in a string can be accessed by using methods such as SubString() and Replace().
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, as in the following example:
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, as in the following example:
string s5 = "Printing backwards"; for (int i = 0; i < s5.Length; i++) { System.Console.Write(s5[s5.Length - i - 1]); // outputs "sdrawkcab gnitnirP" } |
Точные строки: символ @
Символ @ служит для того, чтобы конструктор строк пропускал escape-знаки и переносы строки. Следующие две строки являются идентичными:
string p1 = "\\\\My Documents\\My Files\\"; string p2 = @"\\My Documents\My Files\"; |
Чтобы поставить в точной строке знак двойных кавычек, нужно использовать по два таких знака, как показано в следующем примере:
string s = @"You say ""goodbye"" and I say ""hello"""; |
Доступ к отдельным знакам
К отдельным знакам, содержащимся в строке, можно получить доступ с помощью таких методов как SubString() и Replace().
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" |
Также можно скопировать символы строки в массив символов, как показано в следующем примере.
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]); // outputs "sdrawkcab gnitnirP" } |
Changing Case
To change the letters in a string to uppercase or lowercase, use ToUpper() or ToLower(), as in the following example:
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 != operators, 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 objects also have a CompareTo() method that returns an integer value that is based on whether one string is less-than (<), equal to (==) or greater-than (>) another. When comparing strings, the Unicode value is used, and lowercase has a smaller value than uppercase. For more information about the rules for comparing strings, see CompareTo()()().
// Enter different values for string1 and string2 to // experiement 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 |
Смена регистра
|
|
Чтобы изменить регистр букв в строке (сделать их заглавными или строчными), следует использовать 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" |
Сравнения
Самый простой способ сравнения двух строк — использовать операторы == и !=, осуществляющие сравнение с учетом регистра.
string color1 = "red"; string color2 = "green"; string color3 = "red"; if (color1 == color3) { System.Console.WriteLine("Equal"); } if (color1 != color2) { System.Console.WriteLine("Not equal"); } |
Для строковых объектов также существует метод CompareTo(), возвращающий целочисленное значение, зависящее от того, одна строка меньше (<), равна (==) или больше другой (>). При сравнении строк используется значение Юникода, при этом значение строчных букв меньше, чем значение заглавных. Дополнительные сведения о правилах сравнения строк см. в разделах CompareTo()()().
ß--
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.
Дата добавления: 2019-03-09; просмотров: 261; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!