0% found this document useful (0 votes)
14 views10 pages

C# String and Array Manipulation Techniques

The document contains code snippets in C# for common string and array operations like removing duplicates from an array or string, reversing a string, finding the largest element in an array, counting letters and vowels in a string, and removing vowels from a string. These operations are performed using methods like Distinct(), ToCharArray(), Contains(), IndexOf(), Replace(), and Regex.

Uploaded by

Ravi Shetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

C# String and Array Manipulation Techniques

The document contains code snippets in C# for common string and array operations like removing duplicates from an array or string, reversing a string, finding the largest element in an array, counting letters and vowels in a string, and removing vowels from a string. These operations are performed using methods like Distinct(), ToCharArray(), Contains(), IndexOf(), Replace(), and Regex.

Uploaded by

Ravi Shetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

The Func delegate points to a method that accepts parameters and returns

a value; the Action delegate points to a method that accepts parameters but
does not return a value
Removing duplicate from array

using System;

using [Link];

class GFG{

public static void Main()

// Declare an array of integer type

int[] data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 };

[Link]("Array before removing duplicate values: ");

[Link](data, i => [Link](i));

// Use distinct() function

// To create an array that contain distinct values

int[] unique = [Link]().ToArray();

// Display the final result

[Link]("Array after removing duplicate values: ");

[Link](unique, j => [Link](j));

}
Reverse String

using System;

public class HelloWorld

public static void Main(string[] args)

string Reverse="Palle";

for ( int i=[Link]-1;i>-1;i--)

[Link](Reverse[i]) ;

Or

using System;

using [Link];

class GFG{

public static string Reverse(string Input )

char[] CharArray=[Link]();

string Reverse=[Link];

for ( int i=[Link]-1;i>-1;i--)

{
Reverse+=CharArray[i];

return Reverse;

public static void Main(string[] args)

[Link](Reverse("GeeksForGeeks"));

Removing duplicates in String

using [Link];

using System;

namespace LogicalPrograms

class Program

static void Main(string[] args)

string inputString = "Raveendra";

var uniqueCharArray = [Link]().Distinct().ToArray();

var resultString = new string(uniqueCharArray);


[Link]("After Removing Duplicates : " + resultString);

[Link]();

Or USIng HashTable

using System;

using [Link];

using [Link];

namespace Demo {

class Program {

static void Main(string[] args) {

string myStr = "Ravii";

var unique = new HashSet<char>(myStr);

[Link]("New String after removing duplicates: ");

foreach (char c in unique)

[Link](c);

Or using for loop

// Online C# Editor for free

// Write, Edit and Run your C# code using C# Online Compiler

using System;

public class HelloWorld


{

public static void Main(string[] args)

string Name="Ravii";

string Out=[Link];

for (int i=0;i<[Link];i++)

if (![Link](Name[i]))

Out+=Name[i];

[Link] (Out);

// C# program sort an array in decreasing order and remove -1 values

// using [Link]() and [Link]() Method and remove the duplication and negative value

using System;

using [Link];

using [Link];

class GFG {

// Main Method

public static void Main(string[] args)

{ // declaring and initializing the array

int[] arr = {1, 9, 6, 7, 5, 9,10,-1};

ArrayList a1= new ArrayList();


[Link](arr);

arr=[Link]().ToArray();

[Link]("\n\n Ascending :");

foreach(int value in arr)

{ if(value>0)

[Link](value + " " );

[Link](value);

arr=(int[])[Link](typeof(int));

[Link](arr);

[Link]("\n\n Descending :");

foreach(int value in arr)

[Link](value + " ");

// C# program Biggest element in array

using System;

using [Link];

using [Link];

class GFG {

// Main Method

public static void Main(string[] args)

// declaring and initializing the array

int[] arr = {1, 9, 6, 7, 5, 9,10};


int big =arr[0];

for ( int i=1;i<[Link]; i++)

if (arr[i]>big)

big=arr[i];

[Link]("\n\n Biggest Elemen :"+" "+ big );

COUNT THE LETTER IN THE WORD

// Online C# Editor for free

// Write, Edit and Run your C# code using C# Online Compiler

using System;

using [Link];

public class HelloWorld

public static void Main(string[] args)

string Name="test training";

Name=[Link](" ",[Link]);
while([Link]>0)

[Link](Name[0] + " : ");

int count=0;

for(int j=0;j<[Link];j++)

if(Name[0]==Name[j])

count++;

[Link](count);

Name=[Link](Name[0].ToString(),[Link]);

[Link]();

VOWEL COUNT IN STRING


// Online C# Editor for free

// Write, Edit and Run your C# code using C# Online Compiler

using System;

public class HelloWorld

public static void Main(string[] args)

string Message="Welcome Ravi";

int count=0;

for(int i=0;i<[Link];i++)
{

if(Message[i]=='a' ||Message[i]=='e' ||Message[i]=='i' ||Message[i]=='0' )

count++;

[Link](count);

REMOVING VOWEL IN C# PROGRAM

using System;

using [Link];

public class HelloWorld

public static void Main(string[] args)

string Message="Welcome Ravi";

Message=[Link](Message,"[aeiouAEIOU]","");

[Link](Message);

Common questions

Powered by AI

The document demonstrates best practices such as using the 'Distinct()' method for eliminating duplicates efficiently, employing 'HashSet' for uniqueness constraints, and leveraging LINQ for clear data operations, which aligns with a functional programming approach. Error prevention is supported by avoiding direct manipulation of indices in data processing (e.g., avoiding manual duplicate checks in favor of built-in methods). Maintainability is evidenced by the use of readable code structures, such as named methods for string reversal instead of inline logic, and utilizing lambda expressions to reduce boilerplate code, enhancing readability and reducing the potential for errors .

The 'Distinct()' method in LINQ creates a new enumerable collection that only contains unique elements, effectively removing duplicates from arrays or strings. Its impact on computational efficiency is significant because it reduces redundancy and saves memory by not keeping multiple copies of the same elements. However, depending on the size of the original collection, there might be a trade-off in time complexity, especially if the collection is large and checking for uniqueness involves complex equality comparers .

Counting each letter's occurrence typically involves iterating over the string and maintaining a frequency count using a dictionary or similar data structure. Removing spaces is crucial for accuracy, especially in counting meaningful characters, as spaces do not contribute to the actual content being analyzed. This preprocessing step ensures that only letters are counted, which is particularly important in contexts like character frequency analysis in natural language processing, where spaces could otherwise skew the results .

System.Linq brings advanced data manipulation capabilities to C# by providing a set of methods that operate on sets of data in a declarative manner, often resembling SQL-like queries. Lambda expressions complement LINQ by allowing succinct and anonymous functions that can be passed to these methods, enabling powerful chainable operations such as filtering, projection, and aggregation. This combination enhances readability and reduces boilerplate code, significantly impacting the maintainability and expressiveness of data processing tasks compared to traditional loops .

A HashSet is used to remove duplicates by leveraging its property of not allowing duplicate elements, making it a straightforward method for ensuring each character is unique. The benefit of using a HashSet is its O(1) average time complexity for insertions and lookups, which makes it efficient for such operations. However, HashSet does not maintain the order of insertion, which might be a limitation when the order of characters matters. Also, the overhead of HashSet can be higher than simpler structures for small datasets .

The 'Func' delegate represents a method that accepts parameters and returns a value, while the 'Action' delegate points to a method that accepts parameters but does not return a value. 'Func' is suitable in scenarios where functions are used in a chain of functional operations, such as transformation operations in LINQ queries. 'Action' is ideal for methods intended to perform operations without needing to return data, such as logging operations or UI updates, where the emphasis is on side effects rather than outputs .

Negative values can affect sorting results and necessitate special handling if they represent invalid or placeholder data. For instance, when sorting an array, negative values will initially appear at the beginning in ascending order unless filtered out. Overcoming these challenges involves first filtering the array to remove negative values using methods like LINQ before performing any sorting operations. This preprocessing ensures the resulting dataset only contains relevant data for further operations like sorting and reversing .

Sorting and reversing operations can be combined effectively to achieve specific data arrangements, like a descending sorted array. 'Array.Sort()' provides an efficient means to sort elements, and 'Array.Reverse()' can subsequently invert this order. However, these methods independently modify the array in-place, which can lead to data loss if not handled correctly. Ensuring data integrity might require copying arrays or performing operations on temporary collections. For large datasets, consideration of time complexity and memory usage is essential, as repeated operations could impact performance significantly .

Using regular expressions to remove vowels enhances performance by leveraging the compiled patterns that efficiently match and replace characters in a single pass through the string. This can be more efficient than iterating through each character, reducing overall time complexity. However, potential drawbacks include the overhead of constructing and compiling the regular expression, particularly if the operation is performed frequently or the pattern is complex. Additionally, regular expressions can be less readable and harder to maintain compared to simple iterative methods .

Using a 'for loop' to reverse a string involves iterating from the end of the string to the start and constructing a new reversed string character by character. This method is straightforward but may be less efficient for very long strings due to repeated concatenation. Converting a string to a 'char array' and then reversing it encapsulates this logic into fewer operations, which can be more efficient, especially if using built-in methods that are optimized internally in .NET. The char array method is suitable when performance is a concern or when manipulability of individual characters is needed .

You might also like