codehutch.com

Online Code Repository

C#: Reverse a String

Reversing a string in C# is quite easy. The main concept is to treat the string as an array of characters, which is already built-in in C#, and transfer each character to new container in reverse order. Here are the samples of simple and straightforward functions on how to reverse a string in C#.

Manual reverse transfer using for-loop

public static string ReverseByTransfer(string str)
{
int strlen = str.Length;
char[] arr = new char[strlen];

for (int i = 1; i <= strlen ; i++)
{
arr[i-1] = str[strlen - i];
}

return new string(arr);
}

Convert string to character-array and use Array’s Reverse function

public static string ReverseByConvert(string str)
{
char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}

DOWNLOAD REVERSE STRING CODE

===================



Tags:

XOR Encryption

XOR (Exclusive OR, EOR, EXOR) is a logical operation which results to a true value if exactly one of the two operands has a value of true.

Sample XOR Table

INPUT OUTPUT
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Using this knowledge we can encrypt characters using their binary values. Take for example the string “ENCRYPT”. First, we take the ASCII Code of each character in this string and convert each to their respective binary value.

E - 69 - 1000101
N - 78 - 1001110
C - 67 - 1000011
R - 82 - 1010010
Y - 89 - 1011001
P - 80 - 1010000
T - 84 - 1010100

Note: Small letters have different ASCII values.

Choose a random encryption key, say “X”. X has an ASCII Code of 88 and binary value of 1011000. If we perform XOR on “ENCRYPT” against “X”, we get:

1000101 ^ 1011000 = 0001101 [29]
1001110 ^ 1011000 = 0010110 [22]
1000011 ^ 1011000 = 0011011 [27]
1010010 ^ 1011000 = 0001010 [10]
1011001 ^ 1011000 = 0000001 [1]
1010000 ^ 1011000 = 0001000 [8]
1010100 ^ 1011000 = 0001100 [12]

Looking up these numbers in ASCII Code Table, we get:

Thus, the string “ENCRYPT” will be encrypted to:

Putting it in Codes [C#]

Encrypt:

public static string Encrypt(string orgStr, char keyChar)
{
string encrypted = “”;
for (int i = 0; i < orgStr.Length; i++)
{
encrypted += (char)(orgStr[i] ^ keyChar);
}

return encrypted;
}

Decrypt:

public static string Decrypt(string orgStr, char keyChar)
{
string decrypted = “”;
foreach (char encChar in orgStr.ToCharArray())
{
decrypted += (char)(encChar ^ keyChar);
}

return decrypted;
}

Usage:

string encStr = Encrypt(”TEST”, ‘X’);
Console.WriteLine(”Original String: TEST”);
Console.WriteLine(”Encrypted String: ” + encStr);
Console.WriteLine(”Decrypted String: ” + Decrypt(encStr, ‘X’));

Result:

DOWNLOAD XOR ENCRYPTION CODE

===================



T-SQL can be a powerful tool for developers if exploited. It allows you to programatically manipulate your data on the “database-level”. This post will show a simple T-SQL script on how to create a recursive user-defined function [UDF] that can be used application-wide via a simple query. To demonstrate, we will use one of the most common mathematical problems in which a recursive algorithm can be applied - solving for factorial.

Create a UDF

Create Function [dbo].[Factorial]
(
@n int
)
Returns int

AS
Begin

declare @factorial int

if @n = 0
set @factorial = 1
else
set @factorial = @n * dbo.Factorial(@n - 1) –call it recursively

return @factorial

You can then simply call it in any of your queries like:

select dbo.Factorial(6) –returns 720



Tags:

Here is a sample source code on how to read and load xml file via LINQ, extract the data [using a query] and export it to a CSV file.

The XML file (employee.xml)

<xml>
<Employee id=”1″>
<Name>John Doe</Name>
<Position>President</Position>
<Salary>$500,000</Salary>
</Employee>
<Employee id=”2″>
<Name>Jane Doe</Name>
<Position>Vice President</Position>
<Salary>$250,000</Salary>
</Employee>
<Employee id=”3″>
<Name>Jen Doe</Name>
<Position>Manager</Position>
<Salary>$50,000</Salary>
</Employee>
</xml>


The code

‘Libraries
Imports System
Imports System.IO
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.VisualBasic.FileIO

‘=====================================

‘Read/Load xml file
Dim employees As XElement = XElement.Load(”employee.xml”)
Dim outputData As New StringBuilder

‘query on loaded xml data and output as String Enumeration
Dim xmlData = _
From emp In employees.<Employee> _
Select String.Format(”"”{0}”",”"{1}”",”"{2}”",”"{3}”"”, _
emp.@id, _
emp.<Name>.Value, _
emp.<Position>.Value, _
emp.<Salary>.Value)

‘Traverse enum and append extracted data
For Each row In xmlData
outputData.AppendLine(row)
Next

‘Output as .txt file
File.WriteAllText(”ParsedData.csv”, outputData.ToString)

The output as CSV file (ParsedData.csv)

“1″,”John Doe”,”President”,”$500,000″
“2″,”Jane Doe”,”Vice President”,”$250,000″
“3″,”Jen Doe”,”Manager”,”$50,000″



Tags:

There are cases where using Cursor would do you more harm than good. It uses considerably large amount of resources in your server and not to mention that it can cause leaks if not used correctly (Eg. Open without corresponding Close). That’s why most T-SQL developer often suggest to avoid it whenever possible. Here is a sample code on how to travese a result set and get values of each row using a While Loop instead of a Cursor.

–identity INT (1,1) - surrogate PRIMARY KEY
declare @tempTable table(id int identity(1,1),employeeName varchar(25),employeePosition varchar(25))

insert into @tempTable
select ‘John’,'Manager’

insert into @tempTable
select ‘Joe’,'Vice President’

insert into @tempTable
select ‘Mary’,'Secretary’

declare @rowCount int
select @rowCount = count(*) from @tempTable

declare @counter int
select @counter = 1

while @counter <= @rowCount
begin

select * from @tempTable where id = @counter

select @counter = @counter + 1
end



Tags:

« Previous Entries