Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Friday, April 10, 2009

How to reverse string

   26             string originalString = "123456789";

   27             char[] buffer = originalString.ToCharArray();

   28             Array.Reverse(buffer);

   29             string reversedString = new String(buffer);

   30 

   31             Console.WriteLine();

   32             Console.WriteLine("original string: " + originalString);

   33             Console.WriteLine("reversed string: " + reversedString);

 

image

How to fill String variable.

To fill a string variable, sometimes, they use next way:       const string breakLine = "----------";

Seems, next way (usage one of string’s constructor) will be better:

string line = new string('-', 10);
Console.WriteLine("new string('-', 10) >" + line);

 

Console Output:

image

Monday, May 5, 2008

Comparison of 2 standard c# objects.

    To sort array (or list) of a objects, we need compare 2 objects and define number:

0 - when 2 objects are same;

+1 - when a 1st object more than 2nd;

-1 - when a 1st object less than 2nd.

 

Samples:

Sign of number:

int x;
Console.WriteLine(Environment.NewLine + "int x");
Console.WriteLine("Math.Sign({0}) = {1}", x = 10, Math.Sign(x));
Console.WriteLine("Math.Sign({0}) = {1}", x = -10, Math.Sign(x));
Console.WriteLine("Math.Sign({0}) = {1}", x = 0, Math.Sign(x));


Compare 2 strings:


string s1;
string s2;
bool ignoreCase;
Console.WriteLine();
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "a", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "b", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "a", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "aa", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "bb", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "A", s2 = "b", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\") = {2}", s1 = "B", s2 = "a", String.Compare(s1, s2));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\", {2}) = {3}", s1 = "a", s2 = "A", ignoreCase = false, String.Compare(s1, s2, ignoreCase));
Console.WriteLine("String.Compare(\"{0}\", \"{1}\", {2}) = {3}", s1 = "a", s2 = "A", ignoreCase = true, String.Compare(s1, s2, ignoreCase));



Compare 2 DateTime objects:


DateTime d1;
DateTime d2;
Console.WriteLine();
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2007, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2006, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));
Console.WriteLine("DateTime.Compare({0}, {1}) = {2}", d1 = new DateTime(2008, 10, 1), d2 = new DateTime(2007, 10, 1), DateTime.Compare(d1, d2));



Console output:


consoleSign



Reference:



Friday, May 2, 2008

Sorting with help of delegate Comparison.

    When we use Generic class List(T), we can easy to sort it with help of method Sort and delegate Comparison.

Sample.

Definition of class Data:

internal class Data
{
internal int id;
internal string name;
internal Data(int id, string name)
{
this.id = id;
this.name = name;
}
}



Initialization of List<Data>:



List<Data> dataList = new List<Data>();
dataList.Add(new Data(4, "London"));
dataList.Add(new Data(2, "Rome"));
dataList.Add(new Data(3, "New York"));
dataList.Add(new Data(5, "Paris"));
dataList.Add(new Data(1, "Jerusalem"));

DataServices.PrintList("by original order:", dataList);



Sorting dataList by field id:



dataList.Sort(delegate(Data data1, Data data2) { return data1.id - data2.id; });
DataServices.PrintList("by id:", dataList);



Sorting dataList by field name:



dataList.Sort(delegate(Data data1, Data data2) { return String.Compare(data1.name, data2.name); });
DataServices.PrintList("by name:", dataList);



Console output:



consoleComparison



Reference:



List(T).Sort Method



Comparison(T) Generic Delegate



Using IComparable and IComparer to compare objects

Tuesday, April 29, 2008

ReferencesManager 1.0.2 : Utility to check .NET assembly references.

    New build of ReferencesManager (v1.0.2) is released.

    The build include new command line switch:

-path=<customer path>

which allows to define additional folders to search referenced assemblies. For example:

ReferencesManager.exe Main.dll -path=D:\0;D:\1

Downloading ReferencesManager 1.0.2

Sources can be downloaded from "C# tips samples" project.

References:

Utility to check .NET assembly references

Thursday, April 24, 2008

CSharp (c#) methods String.PadLeft(), String.PadRight().

    When we need to align output of strings we can use method String.PadLeft() or String.PadRight():

Sample:

string[] initialData = new string[] 
{"one", "two",
"three", "four", "five"};

Console.WriteLine("PadLeft sample");
foreach (string item in initialData)
{
string processedItem = item.PadLeft(10, '.');
Console.WriteLine("'{0}'", processedItem);
}

Console.WriteLine("PadRight sample");
foreach (string item in initialData)
{
string processedItem = item.PadRight(10, '.');
Console.WriteLine("'{0}'", processedItem);
}



Console output:



padConsole



Reference:



String.PadLeft Method



String.PadRight Method

Wednesday, April 23, 2008

CSharp (c#) method String.Join().

When we should create a string, which consists of array of strings with a separator usually we use a iterator (for, foreach).

For example,

string[] stringData = new string[] {"one", "two", "three"};
string outputContent1 = "";
foreach (string item in stringData)
{
outputContent1 += item + ";";
}
outputContent1 = outputContent1.Remove(outputContent1.Length - 1);
Debug.Print("output #1: {0}", outputContent1);



Now, we can use csharp (c#) method String.Join:



string outputContent2 = String.Join(";", stringData);
Debug.Print("output #2: {0}", outputContent2);



Output window:



joinOutput



Reference:



String.Join Method

Wednesday, April 16, 2008

How to remove leading and trailing characters from string in csharp (c#).

To remove leading and trailing characters from string in csharp (c#) we can use methods String.Trim(), String.TrimEnd() or String.TrimStart().

Samples:

originalLine = " message with space, ";
actualLine = originalLine.Trim();
DisplayMessage(originalLine, actualLine);


trimOutput1



originalLine = " message with space, ";
actualLine = originalLine.TrimEnd();
DisplayMessage(originalLine, actualLine);



trimOutput2



originalLine = " message with space, ";
actualLine = originalLine.TrimStart();
DisplayMessage(originalLine, actualLine);



trimOutput3



originalLine = " message with space, ";
actualLine = originalLine.Trim(new char[] { ' ', ',' });
DisplayMessage(originalLine, actualLine);


trimOutput4



Sometimes interesting to see implementation of C# methods.



So, let's see method String.Trim(Char[]):



// Removes a string of characters from the ends of this string. 
public String Trim(params char[] trimChars) {
if (null==trimChars || trimChars.Length == 0) {
trimChars=WhitespaceChars;
}
return TrimHelper(trimChars,TrimBoth);
}


and basic method TrimHelper():



private String TrimHelper(char[] trimChars, int trimType) { 
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;

//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
int i = 0;
char ch = this[start];
for( i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

if (trimType !=TrimHead) {
for (end= Length -1; end >= start; end--) {
int i = 0;
char ch = this[end];
for(i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

//Create a new STRINGREF and initialize it from the range determined above.
int len = end -start + 1;
if (len == this.Length) {
// Don't allocate a new string is the trimmed string has not changed.
return this;
}
else {
if( len == 0) {
return String.Empty;
}
return InternalSubString(start, len, false);
}
}





References:



String.Trim Method

Split string to array of strings in csharp (c#).

    When we should divide a string to array of strings by a specific delimiters, we can use method String.Splt().

Samples:

string line = "name,id=1234,,description,user=Jon";



string[] lineItems = line.Split(new char[] { ',' });
DisplayOutput(line, lineItems);


splitOutput1



lineItems = line.Split(new char[] { ',', '=' });
DisplayOutput(line, lineItems);



splitOutput2



lineItems = line.Split(new char[] { ',', '=' }, 2);
DisplayOutput(line, lineItems);


splitOutput3



lineItems = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput4



lineItems = line.Split(new string[] { ",", "id=", "user="}, StringSplitOptions.RemoveEmptyEntries);
DisplayOutput(line, lineItems);



splitOutput5



References:



String.Split Method

Tuesday, April 15, 2008

Utility to check .NET assembly references

Sometimes, when a complex project (many source solutions, dlls, references) is built and run, then we receive a problem with references (here we don't speak about signed assemblies). For example, all dlls has a reference to basic .dll, but a specific .dll has a reference to obsolete version of the basic .dll.

Sample:

MainUtils has a reference to Utils1 (v2.0.0.0) and Utils2 (v2.0.0.0), but Utils2 (v2.0.0.0) has a reference to obsolete version of Utils1 (v1.0.0.0). See folders TestData4References in solution csharp-samples.

referenceDiagram

When a MainUtils will be run, then a error can be shown.

Utility ReferencesManager.exe helps to show all references and output list of all assemblies full names. This information helps to see same assemblies with different versions.

To start the utility it is necessary to type name of initial executable (or .dll) file:

ReferencesManager.exe MainUtils.exe > MainUtils.log

Content of MainUtils.log:

mainUtilsLog

Received log allows to find Utils1 with different versions 1.0.0.0 and 2.0.0.0 and Utils2, which references to Utils1 version 1.0.0.0.

Limitations of version 1.0.1:

  • The utility finds assemblies in GAC and in folder of initial assembly only.
  • The utility doesn't find referenced (in c# source project), but actually not used assemblies.
  • The utility doesn't output list of problematic assemblies.

Downloading ReferencesManager.exe.

References:

Reflector for .NET

Create and Share Flow Charts, Diagrams and More

Wednesday, March 26, 2008

How to convert simple types (basic operations) in c#.

To convert one simple type (for example int), to another simple type (for example float or string) it is suggested to use .NET class BitConverter.

C# code sample:

static void Main()
{
int intData = 0x01020304;
byte[] bytesData = BitConverter. GetBytes(intData);
float floatData = BitConverter.ToSingle(bytesData, 0);
string stringData = BitConverter.ToString(bytesData);
}


Result values (from VS Locals Window):


BitConverterResultsInLocals



Reference:



BitConverter Class

Monday, March 17, 2008

How to convert a byte array to string and back

To convert byte array to string it is suggested to use class Encoding

class ConvertUtils:

public class ConvertUtils
{
public static string ConvertBytesToString(byte[] data)
{
return Encoding.GetEncoding(1251).GetString(data);
}
public static byte[] ConvertStringToBytes(string data)
{
return Encoding.GetEncoding(1251).GetBytes(data);
}
}

Example:

It is a very important to test converting with help of 0xFD..0xFF (253 - 255) values, because a some code pages cannot convert these values correct.

byte[] inputData = new byte[] {0, 1, 2, 3, 0xFD, 0xFE, 0xFF};
string convertedData = ConvertUtils.ConvertBytesToString(inputData);
byte[] outputData = ConvertUtils.ConvertStringToBytes(convertedData);

Results:

watchWindow

Reference

Encoding Class

Sunday, March 2, 2008

C# function String.IsNullOrEmpty()

If it is necessary to check string variable on null and "" (empty), then

function String.IsNullOrEmpty can be used:


c0de with operator 'if'

string getName(string name)

{
if (name == null || name == "")
return "default";
else
return name;
}


code with function Sgtring.IsNullOrEmpty()


string getName_with_function_IsNullOrEmpty(string name)
{
if (String.IsNullOrEmpty(name))
return "default";
else
return name;
}


Sample can be download:

http://code.google.com/p/csharp-tips/source/browse/trunk/string_functions/Program.cs

Additional Links:
String..::.IsNullOrEmpty Method