Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
65
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

bool result;

 

result = String.IsNullOrEmpty(nullString);

// true

result = String.IsNullOrEmpty(emptyString);

// true

result = String.IsNullOrEmpty(whitespaceString);

// false

result = String.IsNullOrEmpty(tabString);

// false

result = String.IsNullOrEmpty(newlineString);

// false

result = String.IsNullOrEmpty(nonEmptyString);

// false

result = String.IsNullOrWhiteSpace(nullString);

// true

result = String.IsNullOrWhiteSpace(emptyString);

// true

result = String.IsNullOrWhiteSpace(tabString);

// true

result = String.IsNullOrWhiteSpace(newlineString);

// true

result

=

String.IsNullOrWhiteSpace(whitespaceString); //

true

result

=

String.IsNullOrWhiteSpace(nonEmptyString);

//

false

Section 11.6: Trimming Unwanted Characters O the Start and/or End of Strings

String.Trim()

string x = " Hello World! "; string y = x.Trim(); // "Hello World!"

string q = "{(Hi!*";

string r = q.Trim( '(', '*', '{' ); // "Hi!"

String.TrimStart() and String.TrimEnd()

string q = "{(Hi*";

string r = q.TrimStart( '{' ); // "(Hi*" string s = q.TrimEnd( '*' ); // "{(Hi"

Section 11.7: Convert Decimal Number to Binary,Octal and Hexadecimal Format

1. To convert decimal number to binary format use base 2

Int32 Number = 15;

Console.WriteLine(Convert.ToString(Number, 2)); //OUTPUT : 1111

2. To convert decimal number to octal format use base 8

int Number = 15;

Console.WriteLine(Convert.ToString(Number, 8)); //OUTPUT : 17

3. To convert decimal number to hexadecimal format use base 16

var Number = 15;

Console.WriteLine(Convert.ToString(Number, 16)); //OUTPUT : f

Section 11.8: Construct a string from Array

The String.Join method will help us to construct a string From array/list of characters or string. This method accepts two parameters. The first one is the delimiter or the separator which will help you to separate each element in the array. And the second parameter is the Array itself.

GoalKicker.com – C# Notes for Professionals

57

String from char array:

string delimiter=",";

char[] charArray = new[] { 'a', 'b', 'c' };

string inputString = String.Join(delimiter, charArray);

Output : a,b,c if we change the delimiter as "" then the output will become abc.

String from List of char:

string delimiter = "|";

List<char> charList = new List<char>() { 'a', 'b', 'c' }; string inputString = String.Join(delimiter, charList);

Output : a|b|c

String from List of Strings:

string delimiter = " ";

List<string> stringList = new List<string>() { "Ram", "is", "a","boy" }; string inputString = String.Join(delimiter, stringList);

Output : Ram is a boy

String from array of strings:

string delimiter = "_";

string[] stringArray = new [] { "Ram", "is", "a","boy" }; string inputString = String.Join(delimiter, stringArray);

Output : Ram_is_a_boy

Section 11.9: Formatting using ToString

Usually we are using String.Format method for formatting purpose, the.ToString is usually used for converting other types to string. We can specify the format along with the ToString method while conversion is taking place, So we can avoid an additional Formatting. Let Me Explain how it works with di erent types;

Integer to formatted string:

int intValue = 10;

string zeroPaddedInteger = intValue.ToString("000"); // Output will be "010"

string customFormat = intValue.ToString("Input value is 0"); // output will be "Input value is 10"

double to formatted string:

double doubleValue = 10.456;

string roundedDouble = doubleValue.ToString("0.00"); // output 10.46 string integerPart = doubleValue.ToString("00"); // output 10

string customFormat = doubleValue.ToString("Input value is 0.0"); // Input value is 10.5

Formatting DateTime using ToString

DateTime currentDate = DateTime.Now; // {7/21/2016 7:23:15 PM}

string dateTimeString = currentDate.ToString("dd-MM-yyyy HH:mm:ss"); // "21-07-2016 19:23:15"

GoalKicker.com – C# Notes for Professionals

58

string dateOnlyString = currentDate.ToString("dd-MM-yyyy"); // "21-07-2016"

string dateWithMonthInWords = currentDate.ToString("dd-MMMM-yyyy HH:mm:ss"); // "21-July-2016 19:23:15"

Section 11.10: Splitting a String by another string

string str = "this--is--a--complete--sentence";

string[] tokens = str.Split(new[] { "--" }, StringSplitOptions.None);

Result:

[ "this", "is", "a", "complete", "sentence" ]

Section 11.11: Splitting a String by specific character

string helloWorld = "hello world, how is it going?"; string[] parts1 = helloWorld.Split(',');

//parts1: ["hello world", " how is it going?"]

string[] parts2 = helloWorld.Split(' ');

//parts2: ["hello", "world,", "how", "is", "it", "going?"]

Section 11.12: Getting Substrings of a given string

string helloWorld = "Hello World!";

string world = helloWorld.Substring(6); //world = "World!" string hello = helloWorld.Substring(0,5); // hello = "Hello"

Substring returns the string up from a given index, or between two indexes (both inclusive).

Section 11.13: Determine whether a string begins with a given sequence

string HelloWorld = "Hello World"; HelloWorld.StartsWith("Hello"); // true HelloWorld.StartsWith("Foo"); // false

Finding a string within a string

Using the System.String.Contains you can find out if a particular string exists within a string. The method returns a boolean, true if the string exists else false.

string s = "Hello World";

bool stringExists = s.Contains("ello"); //stringExists =true as the string contains the substring

Section 11.14: Getting a char at specific index and enumerating the string

You can use the Substring method to get any number of characters from a string at any given location. However, if you only want a single character, you can use the string indexer to get a single character at any given index like you

GoalKicker.com – C# Notes for Professionals

59

do with an array:

string s = "hello";

char c = s[1]; //Returns 'e'

Notice that the return type is char, unlike the Substring method which returns a string type.

You can also use the indexer to iterate through the characters of the string:

string s = "hello"; foreach (char c in s)

Console.WriteLine(c);

/********* This will print each character on a new line: h

e l l o

**********/

Section 11.15: Joining an array of strings into a new one

var parts = new[] { "Foo", "Bar", "Fizz", "Buzz"}; var joined = string.Join(", ", parts);

//joined = "Foo, Bar, Fizz, Buzz"

Section 11.16: Replacing a string within a string

Using the System.String.Replace method, you can replace part of a string with another string.

string s = "Hello World";

s = s.Replace("World", "Universe"); // s = "Hello Universe"

All the occurrences of the search string are replaced.

This method can also be used to remove part of a string, using the String.Empty field:

string s = "Hello World";

s = s.Replace("ell", String.Empty); // s = "Ho World"

Section 11.17: Changing the case of characters within a String

The System.String class supports a number of methods to convert between uppercase and lowercase characters in a string.

System.String.ToLowerInvariant is used to return a String object converted to lowercase.

System.String.ToUpperInvariant is used to return a String object converted to uppercase.

Note: The reason to use the invariant versions of these methods is to prevent producing unexpected culturespecific letters. This is explained here in detail.

Example:

string s = "My String";

GoalKicker.com – C# Notes for Professionals

60