Showing posts with label String Manipulations in C#. Show all posts
Showing posts with label String Manipulations in C#. Show all posts

Saturday, 6 July 2024

IsNullOrEmpty and IsNullOrWhiteSpace

 

Both methods are part of the System namespace and are commonly used in string validation scenarios.

In C#, the String.IsNullOrEmpty and String.IsNullOrWhiteSpace methods are used to check if a string is null, empty, or consists only of white-space characters.

 

String.IsNullOrEmpty is Used to Check Strings is null or Empty

String.IsNullOrWhiteSpace is Used to Check string is null,Empty and Whitespaces



Example String

String.IsNullOrEmpty

String.IsNullOrWhiteSpace

“”

true

true

null

true

true

        

false

true

"\n\t"

false

True

“Hello”

false

false


String.IsNullOrEmpty

  • Purpose: Checks if a string is either null or an empty string ("").
  • Syntax: public static bool IsNullOrEmpty(string value)






String.IsNullOrWhiteSpace

  • Purpose: Checks if a string is null, empty, or consists only of white-space characters (such as spaces, tabs, or newlines).
  • Syntax: public static bool IsNullOrWhiteSpace(string value)









 

Key Differences

  • Whitespace Check: IsNullOrWhiteSpace is more comprehensive as it also checks for white-space characters in addition to null and empty strings,
  • while IsNullOrEmpty only checks for null and empty strings.

 

Use Cases:

  • Use IsNullOrEmpty when you only need to check if a string is null or empty.
  • Use IsNullOrWhiteSpace when you need to check if a string is null, empty, or contains only white-space characters.

Trim Function in String Manipulations

 

`Trim`, `TrimStart`, and `TrimEnd`

In C#, the Trim, TrimStart, and TrimEnd methods are used to remove whitespace or specific characters from the beginning, end, or both ends of a string. Here's an overview of each method with definitions and examples:

 

TrimStart

  • Purpose: Removes all leading whitespace characters from the string, or a set of specified characters.
  • Be default it removes  all leading white spaces If You are not provides any character


String str=”    *#^ Hello Software Engineers ^#*     

string result = str.TrimStart();

output = ”*#^ Hello Software Engineers ^#*     

Note : if nothing provided leading spaces get trimmed

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str.TrimStart(‘*’);

output : ”    *#^ Hello Software Engineers ^#*     

Note : here leading char is space that’s why no trim happen

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str.TrimStart(‘ ’,‘*’,’#’,’^’);

output : “Hello Software Engineers ^#*     

Note : here leading char (‘  ’,‘*’,’#’,’^’) leading chars are removed , order of params not required

 

TrimEnd

  • Purpose: Removes all trailing whitespace characters from the string, or a set of specified characters.
  • Be default it removes  all ending white spaces If You are not provides any character

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str.TrimEnd();

output = ”    *#^ Hello Software Engineers ^#* ”

Note : if nothing provided ending spaces get trimmed

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str. TrimEnd(‘*’);

output : ”    *#^ Hello Software Engineers ^#*     

Note : here End char is space that’s why no trim happen

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str. TrimEnd(‘  ’,‘*’,’#’,’^’);

output : “    *#^ Hello Software Engineers ”

Note : here leading char (‘ ’,‘*’,’#’,’^’) leading chars are removed , order of params not required

 

 

Trim

  • Purpose: Removes all leading and trailing whitespace characters from the string, or a set of specified characters.
  • All leading and ending spaces get trimmed if nothing provided

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str.Trim();

output = ”*#^ Hello Software Engineers ^#* ”

Note : if nothing provided ending spaces get trimmed

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str. Trim(‘*’);

output : ”    *#^ Hello Software Engineers ^#*     

Note : here leading & End char is space that’s why no trim happen

 

String str=”    *#^ Hello Software Engineers ^#*     

string result = str. Trim(‘  ’,‘*’,’#’,’^’);

output : “ Hello Software Engineers ”

Note : here leading & ending char (‘ ’,‘*’,’#’,’^’) are removed , order of params not required


String str=”  *#^ Hello  ^#*   

Parameters

Trim

TrimStart

TrimEnd

None

”*#^ Hello  ^#*”

”*#^ Hello  ^#*  

   *#^ Hello  ^#*”

(‘*’)

  *#^ Hello  ^#*   

  *#^ Hello  ^#*   

  *#^ Hello  ^#*   

(‘  ’,‘*’,’#’,’^’);

“Hello”

”Hello  ^#*   

  *#^ Hello”



Key Points

  • Whitespace Removal: By default, all three methods remove whitespace characters (spaces, tabs, newlines, etc.).
  • Character Removal: You can specify an array of characters to be removed by passing them as arguments to these methods.
  • Usage:
    • Use Trim when you need to remove characters from both the beginning and end of a string.
    • Use TrimStart when you need to remove characters only from the beginning of a string.
    • Use TrimEnd when you need to remove characters only from the end of a string.

Join Method in String Manipulation

 

Join Method Concatenates an array of strings into a single string with a specified separator using String.Join() Method.

 

string result;

string[] fruits = { "Apple", "Banana", "Orange", "Grapes", "Jamakaya", "Bathayi" };

char[] ABCD = { 'A', 'B', 'C', 'D' };

List<string> fruits1 = new List<string>() { "Apple", "Banana", "Orange", "Grapes" };

 

 

//separator and string array as parameters

result = String.Join(", ", fruits);

Output: Apple, Banana, Orange, Grapes, Jamakaya, Bathayi

 

//separator and Char array as parameters

result = String.Join(", ", ABCD);

Output: A, B, C, D

 

// separator and list of strings as parameter

result = String.Join(", ", fruits1);

Output:Apple, Banana, Orange, Grapes

 

//separator and string array , start index and count as parameters

result = String.Join(", ", fruits, 2, 3);

Output: "Orange, Grapes, Jamakaya"

 

 

// separator and string params

result = String.Join(", ", "Apple", "Banana", "Orange", "Grapes", "Jamakaya", "Bathayi");

Output: "Apple, Banana, Orange, Grapes, Jamakaya, Bathayi"

 

 

// separator and int params

result = String.Join(", ", 10, 20, 30, 40, 50, 60);

Output: "10, 20, 30, 40, 50, 60"

 

// separator and mixed num params

result = String.Join(", ", 10.2, 20, 30.02, 40, 50, 60.5);

Output: "10.2, 20, 30.02, 40, 50, 60.5"

 

// separator and char params

result = String.Join(", ", 'A', 'B', 'C', 'D');

Output:"A, B, C, D"

 

// seperator and Mixed datatypes

 result = String.Join(", ", "English",'A', 'B', 'C', 'D',10,20,54,36);

Output : "English, A, B, C, D, 10, 20, 54, 36"

Substring in C#

 

Substring

Extracts a substring (portion of string) from a original string.

It contains two overloaded methods.




Method 1 :  startindex  :-  Extracting from a Specific Position to the End of the String

String Name =”Hello John”;

String Output = Name.Substring(6);  // it extract from 6th index onward total characters

 



Method 2 :  startindex , length :-  extracting a Fixed Length Substring from index we provided

String Name =”Hello John”;

String Output = Name.Substring(6,2); // it extracts from 6th index onward total 2 characters

 






Error Handling

  • ArgumentOutOfRangeException: This exception is thrown if the start index or length is out of the bounds of the string.





Real-Time Use Cases

Extracting File Extensions

string fileName = "document.pdf";

string extension = fileName.Substring(fileName.LastIndexOf('.') + 1);  // "pdf"

 

URL Parsing

string url = "https://www.example.com/path?query=123";

string domain = url.Substring(8, url.IndexOf('/', 8) - 8);   // "www.example.com"

 

Date Parsing, Extracting Usernames, Parsing User Input etc.

 

Performance Considerations

  • Immutability: Since strings in C# are immutable, Substring creates a new string, which can impact performance if used excessively in a loop or with large strings.
  • Memory Usage: Each call to Substring results in a new string being allocated in memory. Be mindful of this in performance-critical applications.

Summary

The Substring method is a powerful tool for string manipulation in C#. It allows for precise extraction of parts of a string based on specified positions and lengths. Whether parsing user input, extracting file extensions, or working with dates, Substring is a versatile method that can be applied in many real-world scenarios. However, it is important to handle possible exceptions and consider performance implications when working with large strings or in performance-critical applications.





Tuesday, 25 June 2024

String Builder Vs String

String v/s String Builder

This Article Provide following details 

  • What is String Builder
  • Strigbuilder vs string
  • What is the need of text modifications in real time application development
  • Stringbuilder inbuilt functions and usage

Prove Following 

  1. Pragmatically Prove string is immutable .
  2. Execution time difference between string and stringbuilder
  3. Memory Usage difference between string and stringbuilder

What is String and string builder ?

In C#, both string and StringBuilder are used to handle text, but they are designed for different scenarios and have distinct characteristics. Here’s a detailed comparison:

The string type is immutable in C#, so we cannot change its content after its creation. This means that if we create a string type object and try to amend it, it will create a new instance of the object in the memory. And if we alter the string a lot of times, it can cause some performance problems.

 

StringBuilder solves this problem, because, unlike string, it can dynamically expand its memory to support any manipulation of its contents




In C#, both string and StringBuilder are used to handle text, they are designed for same purpose, but using it for different scenarios and have distinct characteristics.

Action

String

Stringbuilder

initialization

string name=”ASP4UT”;

Stringbuilder sb=new stringbuilder(“ASP4UT”);

concatenation

name=name+”Tutorial”;

Sb.Append(“Tutorial”);

Format

String.Format(“Name {0} Age {1}”,”Srinivas”,30)

Sb.AppenFormat("Name : {0} Salary {0:C}", Srinivas,157);

Replace

Name.Replace(“oldVal”,”NewVal”)

Sb.Replace(“oldVal”,”NewVal”)


string Characteristics

string objects are immutable, meaning once a string object is created, it cannot be changed.

Any modification to  a string actually creates a new string object, which can lead to performance overhead, especially in loops or repeated concatenations.

Frequent modifications of string objects can lead to high memory usage due to the creation of many temporary objects.


string str = "Hello";
str += " World";                             // Creates a new string object
str += " Welcome";                       // Creates a new string object
str=”Welcome to ASP4UT”;         // Creates a new string object

Note :- here 1 initialization and 3 modifications so to 4 objects are created for str variable.

Console.WriteLine(str);  // Output: Welcome to ASP4UT

StringBuilder Characteristics

StringBuilder objects are mutable, meaning they can be modified without creating new objects. This makes StringBuilder more efficient for repeated modifications, such as loops or concatenating a large number of strings.

StringBuilder reduces memory overhead by minimizing the creation of temporary objects. It maintains an internal buffer to accommodate changes, which can grow as needed.



StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");                         //modify same object
sb.Append(" Welcome To");               //modify same object
sb.Append(" ASP4UT");                   //modify same object

Note :- here while use new operator 1 object created and for every modification or append same object will get update. 

Console.WriteLine(sb.ToString());      // Output: Hello World Welcome To ASP4UT

Comparison

·  string: Ideal for simple and less frequent string operations.

·  StringBuilder: Ideal for complex and frequent string modifications, especially within loops.


String

·  Thread Safety:

  • Immutable objects like string are inherently thread-safe, as their state cannot be modified after creation.

·  Memory Usage:

  • Frequent modifications of string objects can lead to high memory usage due to the creation of many temporary objects.

·  Ease of Use:

  • string provides a rich set of methods and operators for easy manipulation and comparison of text.


stringbuilder

Capacity Management:

  • StringBuilder has a Capacity property that can be used to pre-allocate memory to avoid frequent resizing.

Thread Safety:

  • StringBuilder is not thread-safe. If a StringBuilder instance is to be used by multiple threads, proper synchronization is required.

Memory Usage:

  • StringBuilder reduces memory overhead by minimizing the creation of temporary objects. It maintains an internal buffer to accommodate changes, which can grow as needed.

Comparison Summary

Feature

string

StringBuilder

Mutability

Immutable

Mutable

Performance

Slower for frequent modifications

Faster for frequent modifications

Memory Usage

Higher due to creation of new objects

Lower due to in-place modifications

Thread Safety

Inherently thread-safe

Not thread-safe

Use Case

Simple, infrequent string manipulations

Complex, frequent string manipulations


Reason why string modification required? 

String value concatenation is a fundamental operation in programming and is needed in nearly every project for various reasons. Here are some key reasons why string concatenation is essential:

  •        Building Dynamic Content:
  •        Generating HTML and XML:
  •        Formatting Output:
  •        Query Construction:
  •        File Paths and URLs:
  •        Data Serialization:
  •        Template Rendering:
  •       Configuration Files:
  •        Command Construction:
  •        User Input Handling:

Concatenating user input with predefined text to form complete messages or commands.

Example: userMessage = "User " + userName + " has logged in".



String builder Inbuilt function to manipulate text.

 

StringBuilder sb = new StringBuilder()

Append()

sb.Append("I hope you learned something.");

Append New string value to existing value.

AppendLine()

sb.AppendLine();

Add Line break or line of string value

AppendFormat()

sb.AppendFormat("Name : {0} Salary {0:C}", Srinivas,157);

Append Formated sting to existing

Insert

 

var stringBuilder = new StringBuilder("Hi");

stringBuilder.Insert(2, ", welcome to our blog");

 Insert new value on specific index

Replace

 

sb.Replace("learned", "gained");

Replace specific value with new value

Remove

stringBuilder.Remove(0,8);

Remove text from o index to 8 index

Clear 

 

sb.Clear();

Clear current value


When to use string ?

When you don’t require much string concatenation statements go with string.

 

When to use string builder ?

When you required to concatenate string multiple times in your program go with string builder

 example more than 10 time required to concatenate (not sure this time I will give clear metric )

 

what is the benefit of using string builder compare with string

string builder save execution time memory usage when multiple time concatenate string values.



Program to check  string Crete new object on every modification