The .NET string class is quite comprehensive, yet some common string functions are missing or not entirely obvious. This article provides quick tips on using .NET strings.
Fill a String with Repeating Characters
To fill a string with repeating characters, use the string class constructor. For example, to fill a string with twenty asterisks:
string s = new string( '*', 20 );
Check for Blank String
A blank string can be represented by a null reference or empty string (String.Empty or “”). If you attempt to call a method on a null string, an exception will occur. Hence, to check for a blank string, you should use the new .NET v2.0 static function String.IsNullOrEmpty:
String.IsNullOrEmpty( s )
String.Empty vs. “”? It Doesn’t Matter
There has been endless debate on the Web whether it’s better to represent an empty string with String.Empty or blank quotes “”. However, tests show there is minimal performance difference between String.Empty and “” even when creating a billion empty strings.
Reverse a String
There has been extensive analysis on algorithms to reverse a string. The following is a good balance between speed and clarity and works well with Unicode and alternate character sets:
static public string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); }
Compare Strings
Because a string reference can be null, you should avoid using the equality symbol == or the Compare member function when comparing strings. Instead, use the static String.Compare method. This method has the advantage that it can handle null string references, compare strings ignoring case, and compare strings using a specific culture:
if (String.Compare( s1, s2, true ) == 0)
Convert String to Numeric Value
Each numeric data type such as int, Int32, double, etc. has a static TryParse method that converts a string to that data type without throwing an exception. The method returns a bool whether the string contained a value with the specified data type. For example:
string s = "42"; int i; int.TryParse( s, out i );
Use Literal Strings for File Paths
A literal string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters. This makes literal strings ideal for file paths that naturally contain many backslashes. To create a literal string, add the at-sign @ before the string’s opening quote. For example:
string path = @"C:Program FilesMicrosoft Visual Studio 8SDKv2.0Bingacutil.exe";
String Right
Noticeably absent from the string class is the Right method. But you can replicate it easily using the Substring method. Here is a simple method that wraps this up nicely:
static string Right( string s, int count ) { string newString = String.Empty; if (s != null && count > 0) { int startIndex = s.Length - count; if (startIndex > 0) newString = s.Substring( startIndex, count ); else newString = s; } return newString; }
IndexOf Ignoring Case
The string’s IndexOf methods are all case-sensitive. Fortunately, the Globalization namespace contains the CompareInfo class that includes a case-insensitive IndexOf method. For example:
using System.Globalization;
string s1 = "C# is a GREAT programming language."; string s2 = "great"; CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; int i = Compare.IndexOf( s1, s2, CompareOptions.IgnoreCase );
Is there any difference between String.empty and string.empty (The primitive vs the class)? Is either preferable?
String.Empty is identical to string.Empty.
“The keyword string is simply an alias for the predefined class System.String.” – C# Language Specification 4.2.3
http://msdn2.microsoft.com/En-US/library/aa691153.aspx
Good topic for an article!
http://www.devtopics.com/in-c-a-string-is-a-string/
Can you test the Right string with
s = “HelloWorld”;
Consol.WriteLn(Right(s,20));
private string Right(string s, int count)
{
string newString = String.Empty;
if (!string.IsNullOrEmpty(s) && count > 0)
{
int startIndex = s.Length – count;
if (startIndex > 0)
newString = s.Substring(startIndex, count);
else
newString = s;
}
return newString;
}
Khayralla,
Yes, much better, I’ve updated the article. Thank you.
I’m trying to return a string out of a string.
Ballard WA – Zip code 98005 -400X200.
How would I chopped that off so it returns each string individually.
Hades, Use the String.Split() method.
http://msdn2.microsoft.com/en-us/library/system.string.split.aspx
Hi it’s me again.
I’m trying to return a token start counting from right to left. Is there any way to indicate:
return token 3
starting count from right,
the string is “Charlie brown, 12345, USA”
The reason I want to do from token USA to the left is because the tokens on the left are not consistent.
Some times is Charlie Brown and Linus and so on
“Charlie Brown, Linus, Snoopy, 12345, USA”
Please advice..
Hades, here’s a quick console program to demonstrate:
using System;
namespace TokenRight
{
class Program
{
static void Main( string[] args )
{
string s = “Charlie brown, 12345, USA”;
char[] delimiters = new char[] { ‘ ‘, ‘,’ };
string[] words = s.Split( delimiters, StringSplitOptions.RemoveEmptyEntries );
int index = words.Length – 3;
string thirdWordFromRight = index >= 0 ? words[index] : null;
Console.WriteLine( thirdWordFromRight );
Console.ReadLine();
}
}
}
The example for a literal string is wrong.
You’ll end up with a string for a file path containing two backslash characters for every path seperator.
The corrected version:
string path = @”C:Program FilesMicrosoft Visual Studio 8SDKv2.0Bingacutil.exe”;
Corrie, good catch, fixed!
He guys,
I was asked the following and ever since I’ve been trying to do it unsuccessfully.
string mystring = “random”;
foreach letter move two sites in the alphabet.
then the result would be “r=t, a=b, n=p, d=f, o=q and so on”
Hi Hades,
I would approach your problem like this:
string myString = “random”;
int length = myString.Length;
StringBuilder sb = new StringBuilder( length );
for (int i = 0; i < length; i++) { sb.Append( (char)((int)myString[i] + 2)); } string myStringConverted = sb.ToString();
Hi, i’m stuck trying to count the amount of characters in a textbox, i need to count everything, punctuation and all. Any ideas?
this.TextBox1.Text.Length
Brilliant, lifesaver, cheers.
Question I want to execute a Store proc that uses three variables of type string such as Fname, Lname, Middle Name.
How would I write it so my application executes the Storeproc in my DB taking the Input string I’m typing on my text box. Do I have to generate single quates around my string?
Sp_AddCustomer ‘string1’, ‘string2’, ‘string3’
THis is what I’m trying to do in the button on a web form.
Button1 ()
{
SqlConnection conn = new SqlConnection(“Server=(local);DataBase=Northwind;Integrated Security=SSPI”);
conn.Open();
string name = textBox1.text;
string Lname = textBox2.text;
string Middle = textBox3.text;
rc =CallDBService(“SP_addcustomer”, name, Lname, Middle);
conn.Close();
}
Your code looks right. What’s the problem?
when I execute the webform it says the text.Box1.text to textBox3.text aren’t part of the context
Sounds like a webforms issue, not a string issue.
Hey i’m trying to do a sort and trim the “,” but it’s not happening what do you think is wrong?
{
string input = “1,9,3,4,3,9,1,5,6,78,”;
string array = input;
char[] c = array.ToCharArray();
Array.Sort(c.Trim(new char[] {‘,’}));
Console.WriteLine(c);
Console.ReadLine();
}
Also is there a way to sort them so they the greater numbers are in the middle decresing out without using a function. 123498765
Sorry the previous code is incorrect
{
string input = “1,9,3,4,3,9,1,5,6,78,”;
string array = input.Trim(new char[]{‘,’});
char[] c = array.ToCharArray();
Array.Sort(c);
Console.WriteLine(c);
Console.ReadLine();
}
Hades, your question seemed like a good subject for an article:
https://www.csharp411.com/parse-and-sort-comma-delimited-numbers/
Hey Timm,
I’m trying to create a consolote so I copy files from one FOlder to another but i keep getting an error message saying that my dest file is a folder(I know is a folder)
here is my code
string files = @”C:Documents and Settingsa-hamezaDesktopDataSourcesACATest”;
string[] sfiles = Directory.GetFiles(@”C:Documents and Settingsa-hamezaDesktopDataSourcesACA”);
//foreach (string file in files)
// File.Delete(file);
foreach (string sfile in sfiles)
File.Copy(sfile, files);
Hades, I posted a simple solution here:
https://www.csharp411.com/c-copy-folder-recursively/
this page is very usefull for me! thank you!
This was of great help..!
Hi,
I really find this site useful. And I have been able to apply the codes here in my C# applications
J. Mutunga
From Nairobi Kenya
Very useful article.Timm you write ; tests show there is minimal performance difference between String.Empty and “” even when creating a billion empty strings. May i know who win in minimal performance difference ?
Thanks and regards
Dev
what are the different predefined array and string classes?
please help me! i need it for my subject in Programming Language..
Hey Timm,
Is there a way to search for a string in a collection of Integers.
I’m trying to create a method where you pass a SQL colum data Type Integer and I would like to select the ones aren’t Integers. Sounds Wird but it is happening. I already tried SQL server but i could’t find a way of doing it and Im dealing with terrabytes of data that would take quite a bit doing it manually.
This is the way I’m doing it but it throws an error saying (not all code paths return a value)
——————————————-
static void Main(string[] args)
{
string[] myArray =
{“123″,”446″,”447″,”448″,”449″,”450″,”451″,”452″,”453″,”454″,”455″,”456″,”457″,”458″,”459″,”460″,”461″,”462″,”463″,”464″,”465″,”466″,”467″,”468”,
“469”,”470″,”471″,”472″,”473″,”474″,”475″,”476″,”477″,”478″,”479″,”480″,”481″,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd”,”sdfsd” };
Console.WriteLine(ValidateNumericValue(myArray));
Console.ReadLine();
}// End Of Main
public static string ValidateNumericValue(string[] sValues)
{
bool sNumeric;
int i;
int j;
for (i = 0; i < sValues.Length; i++)
{
sNumeric = int.TryParse(sValues[i], out j);
if (!sNumeric)
{
return sValues[i];
}
}
}
}
You need to make sure all code paths return a value. I find the easiest way to ensure this is to have the last line a return statement. Hence you would modify your method as:
public static string ValidateNumericValue(string[] sValues)
{
string s = null;
int j;
for (int i = 0; i < sValues.Length; i++)
{
if (!int.TryParse(sValues[i], out j))
{
s = sValues[i];
}
}
return s;
}
I’m not convinced this method will accomplish what you want, but it should now compile correctly.
Hey Timm this isn’t compiling I get a unreachable code error in the i++, 🙁
Never mind !!!
abou the Method not acomplishing the task this is a prototype I’ll post my solution when done thanks,
You are the best and this is the best C# Site!!!!
Great Site.
I been going crazy trying to figure this out. I originally was setting connString to the server name and kept getting double \’s. Then I figured I use an app.config key… still the same. I’m new to C# so any pointers will be great
App.Config
Code
string connString;
connString = System.Configuration.ConfigurationManager.AppSettings[“ConnectionString”];
Ends up as
System.Configuration.ConfigurationManager.AppSettings[“ConnectionString”] “server=\\PRESARIOLAPTOP\SQL2K5;database=DvdLibrary;Integrated Security=true;” string
App.Config entry is;
Don’t know why is didn’t paste above… It’s been a long day
One more try..
key=”ConnectionString” value=”server=\PRESARIOLAPTOPSQL2K5;database=DvdLibrary;Integrated Security=true;”
Scratch that. It works find. It just shows in the IDE with the double backslashes. Displaying it in a MessageBox shows it’s formatted correctly
Hi Timm I’m trying to find a file within a Directory by doing a search on the three first element of my FileName(3.0.25)I will alway provide the first three Number in the Code; how ever the file in the directory might have and extra digit 3.0.25.0.
This is What I’m Doing :
DirectoryInfo SourcePath = new DirectoryInfo(@”C:Scirpts”);
int NumberMajor, NumberMinor, ThirdIdx;
NumberMajor = 4;
NumberMinor = 0;
ThirdIdx = 196;
string[] files = Directory.GetFiles(SourcePath.ToString(), String.Format(“{0}.{1}.{2}*.sqc”, NumberMajor, NumberMinor, ThirdIdx));
foreach (string fileName in files)
{
if (File.Exists(fileName))
Console.WriteLine(fileName);
}
Console.ReadLine();
How can I accoplish this by using a REGEX??
A question for you!
How do I do a thing like this:
richtextBox1.AppenText(myString);
My problem si that I have an application where I want to view the content of files. They are sometimes binary, but I still want to view them as text. But then the string that contains the data has a lot of crazy characters in it and when I try to append this in my textbox or richtextbox it “evaluates” the special characters.
How do I get it to display the string myString as it is, with “” and all, no escaping.
Very grateful for any hint on how to accomplish this!
Jonas, good question, perhaps you can find your answer here:
https://www.csharp411.com/cleanstripremove-binary-characters-from-c-string/
Hey Timm,
What I found out is that the solution that I implemented ended up to be easier to code and understand.
I tried a number of Regex expressions to look for the file in the folder but every time the compiler would complain about the path not being valid.
Great post!
Trying to find any of the needles in the haystack. Is there a better way?
NinH(“one*two”,”*”,”two”) <= true
NinH("one*two","*","bucklemyshoe") <= false
NinH("one*two","*","bucklemyoneshoe") <= true
NinH("one*two","*","three*two*one") <= true
static bool NinH(string N, string sep, string H)
{
bool ret = false;
string[] s = { sep };
string[] needles = N.Split(s,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i = 0)
{
ret = true;
break;
}
}
return ret;
}
not sure what happened to the code. missing the If
static bool NinH(string N, string sep, string H)
{
bool ret = false;
string[] s = { sep };
string[] needles = N.Split(s,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i = 0)
{
ret = true;
break;
}
}
return ret;
}
sorry, newb poster…
this is missing from the for loop
“if (H.IndexOf(needles[i]) >= 0)”
i want to take a string as input of any length for my program. Can you help me with the code?
Sadia,
Why couldn’t you pass a long string as an Input.
Strings are reference types which means they live in the heap and the stack has only a references that point to an address in the heap so essentially you could pass and any length.
Could provide some code where you are encountering a problem ??
hi all,
(sorry, my English not good)
I have a problem to compare 2 or more addresses. As you may know, user always write down their address without using fixed format. For example:
People from Microsoft wrote:
People1:
Microsoft Corporation One Microsoft Way Redmond, WA 98052-6399 USA
People2:
Microsoft Corp. One Microsoft Way Redmond, WA 98052 6399 USA
People from Microsoft wrote:
People1:
Microsoft Corporation One Microsoft Way Redmond, WA 98052-6399 USA
People2:
Microsoft Corp. One Microsoft Way Redmond, WA 98052 6399 USA
People from Vodafone wrote:
People3:
Vodafone Limited The Connection Newbury Berkshire
RG14 2FN
People4:
Vodafone Limited, The Connection, Newbury Berkshire
RG 14/2FN
People5:
Vodafone Limited, The Connection, Newbury Berkshire
RG-14 2FN
I want system can recognized those 5 addresses as 2 addresses only.
If anyone know the algorithm or anything that might help, please inform me. Thx. ^^
Hello!
I have a strings such as: s = “asd;# qwe;# zxc”.
I’m splitting it to array as follow:
a = s.Split(new[] { “;#” });
But it is returns me an array without leading spaces:
“asd”, “qwe”, “zxc”.
How can I easily fix this behavior?
Thank you!
hi this is siva
i want this prog code at least for 4th one plss
1. A text box for file name
2. A button named as “Segregate”
3. A two column list box (“Word”, “Times”)
4. Pressing the button should read the file contents and find out each word repeats how many times and display in the list box
While there may be no specific performance difference between using string.Empty or “”, there is a very specific reason for using it. If you create a billion strings equal to “”, you have a billion instances of a string object containing no string data. If you create a billion instances of a string equal to string.Empty, you create a billion references to a global constant.
I don’t imagine the amount of storage thus wasted is considerable on a per-string basis, but in a non-trivial application, consider the number of times you use empty strings, usually temporarily.
Strings are immutable, so when you reassign the variable to a non-empty value, the original empty instance still exists and must be cleaned up. Do you really want every single instance of
MyString = “”;
in the application going to the GC for processing? That may not show up on the benchmarks, but it shows up in consumed CPU cycles. On the other hand, if you used
MyString = string.Empty;
reassignment will simply result in the reference changing to the newly created string.
This is not a new idea. It was fairly common in the olden days (C, C++) to assign a single manifest constant for empty strings and reference it whenever you needed one for initialization, or comparison, or whatever, rather than having a few hundred one-byte ”s floating around in your data-section.
This was especially true since, as processors got bigger than 8 bits, the amount of space actually consumed was usually a multiple of the register size, so while the empty string actually *used* 1 byte, it *consumed*, 2, or 4, or 8 *per instance*.
I have a pop-up properties box where I input a string into a label. I have a need to enter This & That.
I have breakpoints to check as my variable gets set to the value and the helper shows This & That.
But only This That shows up on the label.
How do I get the whole string to show up?
I have tried String.Format(@”{0}”, value);
Doesn’t work.
thanks!
You should write:
label1.Text = “This && That”,
becourse “&” used for selecting shortcuts.
Telling my customer to type in This && That is not an option. I have to make whatever is typed in properly displayed. I have to have a method to catch special chars for people who don’t know what a special char is.
In my public get/set, I have to deal with the customer input as a variable (String s = value;), then display s back on the label, as submitted.
Hi there,
How would you code this … I know it’s regex but I can’t figure out how to start the string compare from a certain character (@) …
I want to check to see if all the characters before the “@” symbol in an email address are all alpha (upper or lower case) or not.
Thanks
Chris
Hi timm,
I am trying to write out a batch file for use in another program, and I need to write out file paths with double backslashes intact. for example, in my file I need:
“C:\Users\BenjaminC\Desktop\texture.tga”
I am currently using StreamWriter.WriteLine, but it outputs the string with single backslashes:
“C:UsersBenjaminCDesktoptexture.tga”
Is there any way to write out the double backslashes without creating new strings with quadruple backslashes everywhere?
Thanks,
Benjamin
@Benjamin: If you are defining your paths at compile-time, you can precede each string definition with an at-sign to preserve the double-backslash:
string path = @”C:\Users\BenjaminC\Desktop\texture.tga”;
However, if you are generating your paths at run-time, then you can use the String.Replace method as follows to replace single-backslashes with double-backslashes:
path = path.Replace( “\”, “\\” );
How about using this for Reversing:
public string Reverse(string stringToReverse)
{
char[] rev = stringToReverse.Reverse().ToArray();
return new string(rev);
}
There may be no performance difference between string.Empty vs. “” but there is a definite behavior difference when building SOAP request in .NET using C#. Using string.Empty will send an empty parameter in the SOAP envelope (e.g. ) whereas “” will not send any parameter.
hi,
i am in need of the c language code which gives the following output..
if we give 1X0X01 as the array input it should count me the number of X’s in the array…and the X should b filled with the adjacent value to X….
ie it should give me the output as 100001
its very important for me……..plzzzz help me out……
thnx in advance……….
hi i am trying to assign a string class=”s” to a variable. if i give it as var=”class=”s””; it is an error. please give me a solution….
Amel,
Try putting a in front of the quotes you want to escape.
var = “class=”s””;
Or you can use ‘ instead if that works for you
var = “class’s'”;
Sorry the last line should be
var = “class=’s’”;
[…] csharp411 […]
how can i display random string elements in my array? in this code:
string[] word = {“APPLE”,”BAG”,”LION”,”HORSE”,”DOG”,”CAT”,”BIRD”};
Console.WriteLine(“word is: {0} “, word.GetValue(0));
how can i display random elements, one at a time?
i hope some one can help me
@Dark: Here is a sample console program that should solve your problem:
using System;
namespace RandomStrings
{
class Program
{
static void Main( string[] args )
{
string[] words = { “APPLE”, “BAG”, “LION”, “HORSE”, “DOG”, “CAT”, “BIRD” };
int count = words.Length;
Random r = new Random();
for (int i = 0; i < 10; i++) { int index = r.Next( count ); Console.WriteLine( "word is: {0} ", words[index] ); } Console.ReadLine(); } } }
thank you very much sir.. i really appreciate ur help.. thank u very much!!!
can someone plz help me in my advance keyword search, i want that while writing first few alphabet in the seachbox all the related comes in a listbox below….
for example like google does…. plz help me out…..
can some one help how to create a timer in associated when typing a string,
the syntax is like this,
when i type a string, and there is a 40 sec. countdown timer so that if the time is over and the user did not finish typing it’s game over…
can anyone help me??/
can some one help me here…
i want to remove randomed array string elements and i’m not using an array list.. is there other way to remove the elements that has been displayed in my program??
hope there’s someone could help me.. 🙂
hey everyone i need help! please….
i need to display my timer and my input string. and i can’t display the timer while im typing the string.. how can i do that??
i’m using c# console app. is it possible??
here is my code:
Console.Write(“nttt{0}”, word[index]);
Console.Write(“ntttType here: “);
input = Console.In.ReadLine();
Console.WriteLine(“ntt”,time = timedata(timer));
Hope someone can help me i need this badly for my project…
@Dark: I don’t think it’s possible with a console program. You probably need to switch to WinForms.
hey everyone i need help! please….
i’m now changing my plan to jumble the random words in my array.. how can i do that and compare if the answer is true?
string[] word = { “LION”, “APPLE”, “BAG”, “HORSE”, “RING”, “DOG” };
Random r = new Random();
int count = word.Length;
for (i = 0; i < 4; i++)
{
int index = r.Next(count);
Console.Write("nttt{0}", word[index]);
Console.Write("ntttType here: ");
input = Console.In.ReadLine();
how can i jumble the random words?
Hope someone can help me
everyone!! is this possible?
i want to type a string while there is a for-loop timer?
is that possible??
and how can i do that?
Dark, use a system timer and in the interval, write to the console. Or spawn a thread that just writes to the console.
The secret is to use positions when you write to the console.
for(int x = 1; x <= 100; x++)
{
Console.SetCursorPosition(5, 5);
Console.Write("{0}", x);
}
This would write out 1 to 100 all in the same poition within the console. SO using some pre-planning you could write all sorts of stuff out to a console window without it ever scrolling.
@Joe, great idea, thanks for commenting!
this isn’t 100% perfect, but it’s a good starting place. tweak as you find necessary (beware of word wrap):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace InputAndTimer
{
class Program
{
static void Main(string[] args)
{
Console.WindowWidth = 130;
Console.WindowHeight = 50;
Console.SetCursorPosition(10, 10);
Console.Write(“Enter A Value: “);
MyTimerThread oTimerThread = new MyTimerThread();
oTimerThread.CurRow = 10;
oTimerThread.CurCol = 25;
Thread oThread = new Thread(new ThreadStart(oTimerThread.RunTheLoop));
oThread.Start();
string sSomeValue = Console.ReadLine();
}
}
internal class MyTimerThread
{
public int CurRow { get; set; }
public int CurCol { get; set; }
internal void RunTheLoop()
{
int iLoop = 0;
while (true)
{
if (iLoop > 0)
{
this.CurCol = Console.CursorLeft;
this.CurRow = Console.CursorTop;
}
iLoop++;
Console.SetCursorPosition(5, 5);
Console.Write(DateTime.Now.ToString(“hh:mm:ss”));
// reset position
Console.SetCursorPosition(this.CurCol, this.CurRow);
Thread.Sleep(1000);
}
}
}
}
I cleaned it up a bit, the properties of the MyTimerThread class weren’t necessary…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace InputAndTimer
{
class Program
{
static void Main(string[] args)
{
Console.WindowWidth = 130;
Console.WindowHeight = 50;
Console.SetCursorPosition(10, 10);
Console.Write(“Enter A Value: “);
MyTimerThread oTimerThread = new MyTimerThread();
Thread oThread = new Thread(new ThreadStart(oTimerThread.RunTheLoop));
oThread.Start();
string sSomeValue = Console.ReadLine();
}
}
internal class MyTimerThread
{
internal void RunTheLoop()
{
int CurCol = 0;
int CurRow = 0;
while (true)
{
// save current cursor position
CurCol = Console.CursorLeft;
CurRow = Console.CursorTop;
// set new position
Console.SetCursorPosition(5, 5);
// write the time
Console.Write(DateTime.Now.ToString(“hh:mm:ss”));
// reset position
Console.SetCursorPosition(CurCol, CurRow);
// pause the thread for a second
Thread.Sleep(1000);
}
}
}
}
Hi guys,
I am in need of help, i want to take a string input from a user and then store each word separated by space in an array (NOT ALLOWED TO USE SPLIT). Any suggestions
@Sarfraz Why aren’t you allowed to use Split? it’s what it’s made for…
Other than that, you’ll have to loop through the string character by character, and evaluate each character. If it’s a space (ascii 32) then that’s where you’d break it up yourself.
how to reverse a string by using substring in C# ?????
there should be one member, 3 methods like access input,finding reverse and display output.
I’m not sure if it’s changed since this article was written, but the == equality operator can handle null strings without issue. If you try doing:
string s1 = null;
string s2 = “stuff”;
if(s1 == s2)
Console.Write(“== says they match”);
if(s1.Equals(s2))
Console.Write(“Equals says they match”);
you’ll find that the first works fine, while the second throws an exception. Granted, using an equality operator for a comparison operation, which was the context of how it was mentioned in the article, is still inappropriate, but the article seems to suggest that it can’t handle null string references at all, which is not correct at this time.
Great article. Thanks for sharing
I want to input a lone string from a user at execution time. I want to count the number of the words in the string and also count the white spaces.?? i try many time with the string mystring.contains(); but it also return the just boolean value. But i want to know how many words in the string and how many white spaces in the string ??? Anyone help me please ……
i want to display the largest word in given string. anyone can help,.
You can reverse the string in One Line code
string a = “Teststring”;
string b = new string(a.ToCharArray().Reverse().ToArray());
OutPut: gnirtstseT
Here’s a blog which benchmarks several different C# techniques to finding a string within a string:
http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-check-if-a-string-occurs-within-a-string
_
For those who are looking for benchmarks, he benchmarks several different ways to convert a string to an int:
http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-convert-a-string-to-an-int
What’s interesting is the fastest way isn’t using any of the native C# methods Convert.ToInt32(), int.TryParse(), or int.Parse().
Definitely worth a read for those that are curious.