Related
I want to count words and spaces in my string. String looks like this:
Command do something ptuf(123) and bo(1).ctq[5] v:0,
I have something like this so far
int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring)
{
if(char.IsLetter(c))
{
count++;
}
}
What should I do to count spaces also?
int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7
Note that both use Char.IsWhiteSpace which assumes other characters than " " as white-space(like newline). Have a look at the remarks section to see which exactly .
you can use string.Split with a space
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
When you get a string array the number of elements is the number of words, and the number of spaces is the number of words -1
if you want to count spaces you can use LINQ :
int count = mystring.Count(s => s == ' ');
This will take into account:
Strings starting or ending with a space.
Double/triple/... spaces.
Assuming that the only word seperators are spaces and that your string is not null.
private static int CountWords(string S)
{
if (S.Length == 0)
return 0;
S = S.Trim();
while (S.Contains(" "))
S = S.Replace(" "," ");
return S.Split(' ').Length;
}
Note: the while loop can also be done with a regex: How do I replace multiple spaces with a single space in C#?
Here's a method using regex. Just something else to consider. It is better if you have long strings with lots of different types of whitespace. Similar to Microsoft Word's WordCount.
var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
int count = Regex.Matches(str, #"[\S]+").Count; // count is 7
For comparison,
var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
str.Count(char.IsWhiteSpace) is 17, while the regex count is still 7.
I've got some ready code to get a list of words in a string:
(extension methods, must be in a static class)
/// <summary>
/// Gets a list of words in the text. A word is any string sequence between two separators.
/// No word is added if separators are consecutive (would mean zero length words).
/// </summary>
public static List<string> GetWords(this string Text, char WordSeparator)
{
List<int> SeparatorIndices = Text.IndicesOf(WordSeparator.ToString(), true);
int LastIndexNext = 0;
List<string> Result = new List<string>();
foreach (int index in SeparatorIndices)
{
int WordLen = index - LastIndexNext;
if (WordLen > 0)
{
Result.Add(Text.Substring(LastIndexNext, WordLen));
}
LastIndexNext = index + 1;
}
return Result;
}
/// <summary>
/// returns all indices of the occurrences of a passed string in this string.
/// </summary>
public static List<int> IndicesOf(this string Text, string ToFind, bool IgnoreCase)
{
int Index = -1;
List<int> Result = new List<int>();
string T, F;
if (IgnoreCase)
{
T = Text.ToUpperInvariant();
F = ToFind.ToUpperInvariant();
}
else
{
T = Text;
F = ToFind;
}
do
{
Index = T.IndexOf(F, Index + 1);
Result.Add(Index);
}
while (Index != -1);
Result.RemoveAt(Result.Count - 1);
return Result;
}
/// <summary>
/// Implemented - returns all the strings in uppercase invariant.
/// </summary>
public static string[] ToUpperAll(this string[] Strings)
{
string[] Result = new string[Strings.Length];
Strings.ForEachIndex(i => Result[i] = Strings[i].ToUpperInvariant());
return Result;
}
In addition to Tim's entry, in case you have padding on either side, or multiple spaces beside each other:
Int32 words = somestring.Split( // your string
new[]{ ' ' }, // break apart by spaces
StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
).Length; // number of "words" remaining
using namespace;
namespace Application;
class classname
{
static void Main(string[] args)
{
int count;
string name = "I am the student";
count = name.Split(' ').Length;
Console.WriteLine("The count is " +count);
Console.ReadLine();
}
}
if you need whitespace count only try this.
string myString="I Love Programming";
var strArray=myString.Split(new char[] { ' ' });
int countSpace=strArray.Length-1;
How about indirectly?
int countl = 0, countt = 0, count = 0;
foreach(char c in str)
{
countt++;
if (char.IsLetter(c))
{
countl++;
}
}
count = countt - countl;
Console.WriteLine("No. of spaces are: "+count);
What's the easiest and fastest way to find a sub-string(template) in a string and replace it with something else following the template's letter case (if all lower case - replace with lowercase, if all upper case - replace with uppercase, if begins with uppercase and so on...)
so if the substring is in curly braces
"{template}" becomes "replaced content"
"{TEMPLATE}" becomes "REPLACED CONTENT" and
"{Template}" becomes "Replaced content" but
"{tEMPLATE}" becomes "rEPLACED CONTENT"
Well, you could use regular expressions and a match evaluator callback like this:
regex = new Regex(#"\{(?<value>.*?)\}",
RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
string replacedText = regex.Replace(<text>,
new MatchEvaluator(this.EvaluateMatchCallback));
And your evaluator callback would do something like this:
private string EvaluateMatchCallback(Match match) {
string templateInsert = match.Groups["value"].Value;
// or whatever
string replacedText = GetReplacementTextBasedOnTemplateValue(templateInsert);
return replacedText;
}
Once you get the regex match value you can just do a case-sensitive comparison and return the correct replacement value.
EDIT I sort of assumed you were trying to find the placeholders in a block of text rather than worry about the casing per se, if your pattern is valid all the time then you can just check the first two characters of the placeholder itself and that will tell you the casing you need to use in the replacement expression:
string foo = "teMPLATE";
if (char.IsLower(foo[0])) {
if (char.IsLower(foo[1])) {
// first lower and second lower
}
else {
// first lower and second upper
}
}
else {
if (char.IsLower(foo[1])) {
// first upper and second lower
}
else {
// first upper and second upper
}
}
I would still use a regular expression to match the replacement placeholder, but that's just me.
You can check the case of the first two letters of the placeholder and choose one of the four case transforming strategies for the inserted text.
public static string Convert(string input, bool firstIsUpper, bool restIsUpper)
{
string firstLetter = input.Substring(0, 1);
firstLetter = firstIsUpper ? firstLetter.ToUpper() : firstLetter.ToLower();
string rest = input.Substring(1);
rest = restIsUpper ? rest.ToUpper() : rest.ToLower();
return firstLetter + rest;
}
public static string Replace(string input, Dictionary<string, string> valueMap)
{
var ms = Regex.Matches(input, "{(\\w+?)}");
int i = 0;
var sb = new StringBuilder();
for (int j = 0; j < ms.Count; j++)
{
string pattern = ms[j].Groups[1].Value;
string key = pattern.ToLower();
bool firstIsUpper = char.IsUpper(pattern[0]);
bool restIsUpper = char.IsUpper(pattern[1]);
sb.Append(input.Substring(i, ms[j].Index - i));
sb.Append(Convert(valueMap[key], firstIsUpper, restIsUpper));
i = ms[j].Index + ms[j].Length;
}
return sb.ToString();
}
public static void DoStuff()
{
Console.WriteLine(Replace("--- {aAA} --- {AAA} --- {Aaa}", new Dictionary<string,string> {{"aaa", "replacement"}}));
}
Ended up doing that:
public static string ReplaceWithTemplate(this string original, string pattern, string replacement)
{
var template = Regex.Match(original, pattern, RegexOptions.IgnoreCase).Value.Remove(0, 1);
template = template.Remove(template.Length - 1);
var chars = new List<char>();
var isLetter = false;
for (int i = 0; i < replacement.Length; i++)
{
if (i < (template.Length)) isLetter = Char.IsUpper(template[i]);
chars.Add(Convert.ToChar(
isLetter ? Char.ToUpper(replacement[i])
: Char.ToLower(replacement[i])));
}
return new string(chars.ToArray());
}
I have a string called "hello world"
I need to replace the word "world" to "csharp"
for this I use:
string.Replace("World", "csharp");
but as a result, I don't get the string replaced. The reason is case sensitiveness. The original string contains "world" whereas I'm trying to replace "World".
Is there any way to avoid this case sensitiveness in string.Replace method?
You could use a Regex and perform a case insensitive replace:
class Program
{
static void Main()
{
string input = "hello WoRlD";
string result =
Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
Console.WriteLine(result); // prints "hello csharp"
}
}
var search = "world";
var replacement = "csharp";
string result = Regex.Replace(
stringToLookInto,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
The Regex.Escape is useful if you rely on user input which can contains Regex language elements
Update
Thanks to comments, you actually don't have to escape the replacement string.
Here is a small fiddle that tests the code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var tests = new[] {
new { Input="abcdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="ABCdef", Search="abc", Replacement="xyz", Expected="xyzdef" },
new { Input="A*BCdef", Search="a*bc", Replacement="xyz", Expected="xyzdef" },
new { Input="abcdef", Search="abc", Replacement="x*yz", Expected="x*yzdef" },
new { Input="abcdef", Search="abc", Replacement="$", Expected="$def" },
};
foreach(var test in tests){
var result = ReplaceCaseInsensitive(test.Input, test.Search, test.Replacement);
Console.WriteLine(
"Success: {0}, Actual: {1}, {2}",
result == test.Expected,
result,
test
);
}
}
private static string ReplaceCaseInsensitive(string input, string search, string replacement){
string result = Regex.Replace(
input,
Regex.Escape(search),
replacement.Replace("$","$$"),
RegexOptions.IgnoreCase
);
return result;
}
}
Its output is:
Success: True, Actual: xyzdef, { Input = abcdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = ABCdef, Search = abc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: xyzdef, { Input = A*BCdef, Search = a*bc, Replacement = xyz, Expected = xyzdef }
Success: True, Actual: x*yzdef, { Input = abcdef, Search = abc, Replacement = x*yz, Expected = x*yzdef}
Success: True, Actual: $def, { Input = abcdef, Search = abc, Replacement = $, Expected = $def }
2.5X FASTER and MOST EFFECTIVE method than other's regular expressions methods:
/// <summary>
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another
/// specified string according the type of search to use for the specified string.
/// </summary>
/// <param name="str">The string performing the replace method.</param>
/// <param name="oldValue">The string to be replaced.</param>
/// <param name="newValue">The string replace all occurrences of <paramref name="oldValue"/>.
/// If value is equal to <c>null</c>, than all occurrences of <paramref name="oldValue"/> will be removed from the <paramref name="str"/>.</param>
/// <param name="comparisonType">One of the enumeration values that specifies the rules for the search.</param>
/// <returns>A string that is equivalent to the current string except that all instances of <paramref name="oldValue"/> are replaced with <paramref name="newValue"/>.
/// If <paramref name="oldValue"/> is not found in the current instance, the method returns the current instance unchanged.</returns>
[DebuggerStepThrough]
public static string Replace(this string str,
string oldValue, string newValue,
StringComparison comparisonType)
{
// Check inputs.
if (str == null)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentNullException(nameof(str));
}
if (str.Length == 0)
{
// Same as original .NET C# string.Replace behavior.
return str;
}
if (oldValue == null)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentNullException(nameof(oldValue));
}
if (oldValue.Length == 0)
{
// Same as original .NET C# string.Replace behavior.
throw new ArgumentException("String cannot be of zero length.");
}
//if (oldValue.Equals(newValue, comparisonType))
//{
//This condition has no sense
//It will prevent method from replacesing: "Example", "ExAmPlE", "EXAMPLE" to "example"
//return str;
//}
// Prepare string builder for storing the processed string.
// Note: StringBuilder has a better performance than String by 30-40%.
StringBuilder resultStringBuilder = new StringBuilder(str.Length);
// Analyze the replacement: replace or remove.
bool isReplacementNullOrEmpty = string.IsNullOrEmpty(newValue);
// Replace all values.
const int valueNotFound = -1;
int foundAt;
int startSearchFromIndex = 0;
while ((foundAt = str.IndexOf(oldValue, startSearchFromIndex, comparisonType)) != valueNotFound)
{
// Append all characters until the found replacement.
int charsUntilReplacment = foundAt - startSearchFromIndex;
bool isNothingToAppend = charsUntilReplacment == 0;
if (!isNothingToAppend)
{
resultStringBuilder.Append(str, startSearchFromIndex, charsUntilReplacment);
}
// Process the replacement.
if (!isReplacementNullOrEmpty)
{
resultStringBuilder.Append(newValue);
}
// Prepare start index for the next search.
// This needed to prevent infinite loop, otherwise method always start search
// from the start of the string. For example: if an oldValue == "EXAMPLE", newValue == "example"
// and comparisonType == "any ignore case" will conquer to replacing:
// "EXAMPLE" to "example" to "example" to "example" … infinite loop.
startSearchFromIndex = foundAt + oldValue.Length;
if (startSearchFromIndex == str.Length)
{
// It is end of the input string: no more space for the next search.
// The input string ends with a value that has already been replaced.
// Therefore, the string builder with the result is complete and no further action is required.
return resultStringBuilder.ToString();
}
}
// Append the last part to the result.
int charsUntilStringEnd = str.Length - startSearchFromIndex;
resultStringBuilder.Append(str, startSearchFromIndex, charsUntilStringEnd);
return resultStringBuilder.ToString();
}
Note: ignore case == StringComparison.OrdinalIgnoreCase as parameter for StringComparison comparisonType. It is the fastest, case-insensitive way to replace all values.
Advantages of this method:
High CPU and MEMORY efficiency;
It is the fastest solution, 2.5 times faster than other's methods
with regular expressions (proof in the end);
Suitable for removing parts from the input string (set newValue to
null), optimized for this;
Same as original .NET C# string.Replace behavior, same exceptions;
Well commented, easy to understand;
Simpler – no regular expressions. Regular expressions are always slower because of their versatility (even compiled);
This method is well tested and there are no hidden flaws like infinite loop in other's solutions, even highly rated:
#AsValeO: Not works with Regex language elements, so it's not
universal method
#Mike Stillion: There is a problem with this code. If the text in new
is a superset of the text in old, this can produce an endless loop.
Benchmark-proof: this solution is 2.59X times faster than regex from #Steve B., code:
// Results:
// 1/2. Regular expression solution: 4486 milliseconds
// 2/2. Current solution: 1727 milliseconds — 2.59X times FASTER! than regex!
// Notes: the test was started 5 times, the result is an average; release build.
const int benchmarkIterations = 1000000;
const string sourceString = "aaaaddsdsdsdsdsd";
const string oldValue = "D";
const string newValue = "Fod";
long totalLenght = 0;
Stopwatch regexStopwatch = Stopwatch.StartNew();
string tempString1;
for (int i = 0; i < benchmarkIterations; i++)
{
tempString1 = sourceString;
tempString1 = ReplaceCaseInsensitive(tempString1, oldValue, newValue);
totalLenght = totalLenght + tempString1.Length;
}
regexStopwatch.Stop();
Stopwatch currentSolutionStopwatch = Stopwatch.StartNew();
string tempString2;
for (int i = 0; i < benchmarkIterations; i++)
{
tempString2 = sourceString;
tempString2 = tempString2.Replace(oldValue, newValue,
StringComparison.OrdinalIgnoreCase);
totalLenght = totalLenght + tempString2.Length;
}
currentSolutionStopwatch.Stop();
Original idea – #Darky711; thanks #MinerR for StringBuilder.
Lots of suggestions using Regex. How about this extension method without it:
public static string Replace(this string str, string old, string #new, StringComparison comparison)
{
#new = #new ?? "";
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(#new, comparison))
return str;
int foundAt = 0;
while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
{
str = str.Remove(foundAt, old.Length).Insert(foundAt, #new);
foundAt += #new.Length;
}
return str;
}
Extensions make our lives easier:
static public class StringExtensions
{
static public string ReplaceInsensitive(this string str, string from, string to)
{
str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
return str;
}
}
You can use the Microsoft.VisualBasic namespace to find this helper function:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
.Net Core has this method built-in:
Replace(String, String, StringComparison) Doc. Now we can simply write:
"...".Replace("oldValue", "newValue", StringComparison.OrdinalIgnoreCase)
Modified #Darky711's answer to use the passed in comparison type and match the framework replace naming and xml comments as closely as possible.
/// <summary>
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
/// </summary>
/// <param name="str">The string performing the replace method.</param>
/// <param name="oldValue">The string to be replaced.</param>
/// <param name="newValue">The string replace all occurrances of oldValue.</param>
/// <param name="comparisonType">Type of the comparison.</param>
/// <returns></returns>
public static string Replace(this string str, string oldValue, string #newValue, StringComparison comparisonType)
{
#newValue = #newValue ?? string.Empty;
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(oldValue) || oldValue.Equals(#newValue, comparisonType))
{
return str;
}
int foundAt;
while ((foundAt = str.IndexOf(oldValue, 0, comparisonType)) != -1)
{
str = str.Remove(foundAt, oldValue.Length).Insert(foundAt, #newValue);
}
return str;
}
(Edited: wasn't aware of the `naked link' problem, sorry about that)
Taken from here:
string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
Seems you are not the first to complain of the lack of case insensitive string.Replace.
I have wrote extension method:
public static string ReplaceIgnoreCase(this string source, string oldVale, string newVale)
{
if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
return source;
var stringBuilder = new StringBuilder();
string result = source;
int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
while (index >= 0)
{
if (index > 0)
stringBuilder.Append(result.Substring(0, index));
if (newVale.IsNullOrEmpty().IsNot())
stringBuilder.Append(newVale);
stringBuilder.Append(result.Substring(index + oldVale.Length));
result = stringBuilder.ToString();
index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
}
return result;
}
I use two additional extension methods for previous extension method:
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
public static bool IsNot(this bool val)
{
return val == false;
}
Doesn't this work: I cant imaging anything else being much quicker or easier.
public static class ExtensionMethodsString
{
public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
{
string working = thisString;
int index = working.IndexOf(oldValue, stringComparison);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, stringComparison);
}
return working;
}
}
Extending Petrucio's answer with Regex.Escape on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):
public static class StringExtensions
{
public static string ReplaceIgnoreCase(this string str, string from, string to)
{
return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
}
}
Which will produce the following expected results:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // heLLo wOrld
However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace that is just case-insensitive:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // Hi heLLo Universe
Using #Georgy Batalov solution I had a problem when using the following example
string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com";
string replaced = original.ReplaceIgnoreCase(",DC=", ".")
Below is how I rewrote his extension
public static string ReplaceIgnoreCase(this string source, string oldVale,
string newVale)
{
if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
return source;
var stringBuilder = new StringBuilder();
string result = source;
int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
bool initialRun = true;
while (index >= 0)
{
string substr = result.Substring(0, index);
substr = substr + newVale;
result = result.Remove(0, index);
result = result.Remove(0, oldVale.Length);
stringBuilder.Append(substr);
index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
}
if (result.Length > 0)
{
stringBuilder.Append(result);
}
return stringBuilder.ToString();
}
My this Method could Ignore Case as well as Select Only Whole Word
public static string Replace(this string s, string word, string by, StringComparison stringComparison, bool WholeWord)
{
s = s + " ";
int wordSt;
StringBuilder sb = new StringBuilder();
while (s.IndexOf(word, stringComparison) > -1)
{
wordSt = s.IndexOf(word, stringComparison);
if (!WholeWord || ((wordSt == 0 || !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt - 1, 1)))) && !Char.IsLetterOrDigit(char.Parse(s.Substring(wordSt + word.Length, 1)))))
{
sb.Append(s.Substring(0, wordSt) + by);
}
else
{
sb.Append(s.Substring(0, wordSt + word.Length));
}
s = s.Substring(wordSt + word.Length);
}
sb.Append(s);
return sb.ToString().Substring(0, sb.Length - 1);
}
Another way is to ignore the case sensitivity in String.Replace() using the option StringComparison.CurrentCultureIgnoreCase
string.Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase)
I recommend the StringComparison.CurrentCultureIgnoreCase method as proposed by ZZY / Gama Sharma. This is just another technique that could be used with LINQ:
List<string> ItemsToRedact = new List<string> { "star", "citizen", "test", "universe"};
string Message = "Just like each sTaR is unique yet mAkes the uniVERSE what it is, the light in you makes you who you are";
List<string> ReplacementList = Message.Split(' ').Where(x => ItemsToRedact.Contains(x.ToLower())).ToList();
foreach (var word in ReplacementList)
{
Message = Message.Replace(word, "[Redacted] ");
}
Console.WriteLine(Message);
returns: Just like each [Redacted] is unique yet mAkes the [Redacted] what it is, the light in you makes you who you are
This code could be further distilled but I broke it up for readability
Below function is to remove all match word like (this) from the string set. By Ravikant Sonare.
private static void myfun()
{
string mystring = "thiTHISThiss This THIS THis tThishiThiss. Box";
var regex = new Regex("this", RegexOptions.IgnoreCase);
mystring = regex.Replace(mystring, "");
string[] str = mystring.Split(' ');
for (int i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
mystring = mystring.Replace(str[i].ToString(), string.Empty);
}
}
Console.WriteLine(mystring);
}
You can also try the Regex class.
var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );
Use this, Tested and 100% Worked!
For VB.NET
Dim myString As String
Dim oldValue As String
Dim newValue As String
myString = Form1.TextBox1.Text
oldValue = TextBox1.Text
newValue = TextBox2.Text
Dim working As String = myString
Dim index As Integer = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase)
While index <> -1
working = working.Remove(index, oldValue.Length)
working = working.Insert(index, newValue)
index = index + newValue.Length
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase)
Form1.TextBox1.Text = working
End While
For C#
private void Button2_Click(System.Object sender, System.EventArgs e)
{
string myString;
string oldValue;
string newValue;
myString = Form1.TextBox1.Text;
oldValue = TextBox1.Text;
newValue = TextBox2.Text;
string working = myString;
int index = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase);
Form1.TextBox1.Text = working;
}
}
I prefer this - "Hello World".ToLower().Replace( "world", "csharp" );
I have a compressed string value I'm extracting from an import file. I need to format this into a parcel number, which is formatted as follows: ##-##-##-###-###. So therefore, the string "410151000640" should become "41-01-51-000-640". I can do this with the following code:
String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));
However, The string may not be all numbers; it could have a letter or two in there, and thus the conversion to the int will fail. Is there a way to do this on a string so every character, regardless of if it is a number or letter, will fit into the format correctly?
Regex.Replace("410151000640", #"^(.{2})(.{2})(.{2})(.{3})(.{3})$", "$1-$2-$3-$4-$5");
Or the slightly shorter version
Regex.Replace("410151000640", #"^(..)(..)(..)(...)(...)$", "$1-$2-$3-$4-$5");
I would approach this by having your own formatting method, as long as you know that the "Parcel Number" always conforms to a specific rule.
public static string FormatParcelNumber(string input)
{
if(input.length != 12)
throw new FormatException("Invalid parcel number. Must be 12 characters");
return String.Format("{0}-{1}-{2}-{3}-{4}",
input.Substring(0,2),
input.Substring(2,2),
input.Substring(4,2),
input.Substring(6,3),
input.Substring(9,3));
}
This should work in your case:
string value = "410151000640";
for( int i = 2; i < value.Length; i+=3){
value = value.Insert( i, "-");
}
Now value contains the string with dashes inserted.
EDIT
I just now saw that you didn't have dashes between every second number all the way, to this will require a small tweak (and makes it a bit more clumsy also I'm afraid)
string value = "410151000640";
for( int i = 2; i < value.Length-1; i+=3){
if( value.Count( c => c == '-') >= 3) i++;
value = value.Insert( i, "-");
}
If its part of UI you can use MaskedTextProvider in System.ComponentModel
MaskedTextProvider prov = new MaskedTextProvider("aa-aa-aa-aaa-aaa");
prov.Set("41x151000a40");
string result = prov.ToDisplayString();
Here is a simple extension method with some utility:
public static string WithMask(this string s, string mask)
{
var slen = Math.Min(s.Length, mask.Length);
var charArray = new char[mask.Length];
var sPos = s.Length - 1;
for (var i = mask.Length - 1; i >= 0 && sPos >= 0;)
if (mask[i] == '#') charArray[i--] = s[sPos--];
else
charArray[i] = mask[i--];
return new string(charArray);
}
Use it as follows:
var s = "276000017812008";
var mask = "###-##-##-##-###-###";
var dashedS = s.WithMask(mask);
You can use it with any string and any character other than # in the mask will be inserted. The mask will work from right to left. You can tweak it to go the other way if you want.
Have fun.
If i understodd you correctly youre looking for a function that removes all letters from a string, aren't you?
I have created this on the fly, maybe you can convert it into c# if it's what you're looking for:
Dim str As String = "410151000vb640"
str = String.Format("{0:##-##-##-###-###}", Convert.ToInt64(MakeNumber(str)))
Public Function MakeNumber(ByVal stringInt As String) As String
Dim sb As New System.Text.StringBuilder
For i As Int32 = 0 To stringInt.Length - 1
If Char.IsDigit(stringInt(i)) Then
sb.Append(stringInt(i))
End If
Next
Return sb.ToString
End Function
How can I extract a substring which is composed of the rightmost six letters from another string?
Ex: my string is "PER 343573". Now I want to extract only "343573".
How can I do this?
string SubString = MyString.Substring(MyString.Length-6);
Write an extension method to express the Right(n); function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.
public static string Right(this string sValue, int iMaxLength)
{
//Check if the value is valid
if (string.IsNullOrEmpty(sValue))
{
//Set valid empty string as string could be null
sValue = string.Empty;
}
else if (sValue.Length > iMaxLength)
{
//Make the string no longer than the max length
sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
}
//Return the string
return sValue;
}
Probably nicer to use an extension method:
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
}
Usage
string myStr = "PER 343573";
string subStr = myStr.Right(6);
using System;
public static class DataTypeExtensions
{
#region Methods
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
#endregion
}
Shouldn't error, returns nulls as empty string, returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);
MSDN
String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);
EDIT: too slow...
if you are not sure of the length of your string, but you are sure of the words count (always 2 words in this case, like 'xxx yyyyyy') you'd better use split.
string Result = "PER 343573".Split(" ")[1];
this always returns the second word of your string.
This isn't exactly what you are asking for, but just looking at the example, it appears that you are looking for the numeric section of the string.
If this is always the case, then a good way to do it would be using a regular expression.
var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
Since you are using .NET, which all compiles to MSIL, just reference Microsoft.VisualBasic, and use Microsoft's built-in Strings.Right method:
using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);
No need to create a custom extension method or other work. The result is achieved with one reference and one simple line of code.
As further info on this, using Visual Basic methods with C# has been documented elsewhere. I personally stumbled on it first when trying to parse a file, and found this SO thread on using the Microsoft.VisualBasic.FileIO.TextFieldParser class to be extremely useful for parsing .csv files.
Use this:
String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
numbers = text.Substring(text.Length - 6);
}
Guessing at your requirements but the following regular expression will yield only on 6 alphanumerics before the end of the string and no match otherwise.
string result = Regex.Match("PER 343573", #"[a-zA-Z\d]{6}$").Value;
var str = "PER 343573";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "343573"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "343573"
this supports any number of character in the str. the alternative code not support null string. and, the first is faster and the second is more compact.
i prefer the second one if knowing the str containing short string. if it's long string the first one is more suitable.
e.g.
var str = "";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // ""
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // ""
or
var str = "123";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "123"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "123"
Another solution that may not be mentioned
S.Substring(S.Length < 6 ? 0 : S.Length - 6)
Use this:
string mystr = "PER 343573";
int number = Convert.ToInt32(mystr.Replace("PER ",""));
Null Safe Methods :
Strings shorter than the max length returning the original string
String Right Extension Method
public static string Right(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());
String Left Extension Method
public static string Left(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Take(count));
Here's the solution I use...
It checks that the input string's length isn't lower than the asked length. The solutions I see posted above don't take this into account unfortunately - which can lead to crashes.
/// <summary>
/// Gets the last x-<paramref name="amount"/> of characters from the given string.
/// If the given string's length is smaller than the requested <see cref="amount"/> the full string is returned.
/// If the given <paramref name="amount"/> is negative, an empty string will be returned.
/// </summary>
/// <param name="string">The string from which to extract the last x-<paramref name="amount"/> of characters.</param>
/// <param name="amount">The amount of characters to return.</param>
/// <returns>The last x-<paramref name="amount"/> of characters from the given string.</returns>
public static string GetLast(this string #string, int amount)
{
if (#string == null) {
return #string;
}
if (amount < 0) {
return String.Empty;
}
if (amount >= #string.Length) {
return #string;
} else {
return #string.Substring(#string.Length - amount);
}
}
This is the method I use: I like to keep things simple.
private string TakeLast(string input, int num)
{
if (num > input.Length)
{
num = input.Length;
}
return input.Substring(input.Length - num);
}
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
Just a thought:
public static string Right(this string #this, int length) {
return #this.Substring(Math.Max(#this.Length - length, 0));
}
Without resorting to the bit converter and bit shifting (need to be sure of encoding)
this is fastest method I use as an extension method 'Right'.
string myString = "123456789123456789";
if (myString > 6)
{
char[] cString = myString.ToCharArray();
Array.Reverse(myString);
Array.Resize(ref myString, 6);
Array.Reverse(myString);
string val = new string(myString);
}
I use the Min to prevent the negative situations and also handle null strings
// <summary>
/// Returns a string containing a specified number of characters from the right side of a string.
/// </summary>
public static string Right(this string value, int length)
{
string result = value;
if (value != null)
result = value.Substring(0, Math.Min(value.Length, length));
return result;
}
using Microsoft.visualBasic;
public class test{
public void main(){
string randomString = "Random Word";
print (Strings.right(randomString,4));
}
}
output is "Word"
//Last word of string :: -> sentence
var str ="A random sentence";
var lword = str.Substring(str.LastIndexOf(' ') + 1);
//Last 6 chars of string :: -> ntence
var n = 6;
var right = str.Length >n ? str.Substring(str.Length - n) : "";