Call to replace comma with nothing in C# not working - c#

My code below is supposed to take a number string input and then check if the string has decimals or commas then if true it should replace them with nothing or just get rid of them then it should keep adding leading zeroes to the string until the length of the numbers in the string is equal to 13. My code prints 000123,560789for input 12,560.789 which is an incorrect output because the comma shouldn't be there.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string xcom = "123,560.789";
Console.WriteLine(FormatNumber(xcom));
}
static string FormatNumber(string text){
string prm = text;
string ret = string.Empty;
if(prm.Contains(",")){
ret = prm.Replace(",","");
}
if(prm.Contains(".")){
ret = prm.Replace(".","");
}
//keep adding trailing zeroes till the length is 13
while(ret.Length<13){
ret = "0"+ret ;
}
return ret;
}
}

You need to use ret instead of prm in second if, also it is better to consistently work with the same variable for checks:
string ret = prm;
...
if(ret.Contains("."))
{
ret = ret.Replace(".","");
}
Otherwise you are working with the unmodified instance (i.e. original string - in ret = prm.Replace(".", "");, prm is not affected by previous Replace, strings are immutable in C# - check out the docs).
And the checks are not needed here, just chain the Replace calls:
string ret = prm.Replace(",","").Replace(".","");
And you can use string.PadLeft(Int32, Char) instead of writing it manually:
string ret = prm.Replace(",", "")
.Replace(".", "")
.PadLeft(13, '0');
return ret;

Related

Console.Writeline escape character from variable

I've got an extension method that converts me ulong into a string value with some kind of encryption. I want to output them as they are just by using Console.WriteLine, in most scenarios it works but there is a problem with values with escapes characters. For example "(V\\\|RN" outputs just "(V\|RN".
var result = id.IdToCode();
Console.WriteLine(result);
or
Console.WriteLine(id.IdToCode());
The method IdToCode returns stringBuilder.ToString()
I've tried many combinations with putting somewhere # to return the string as it is but without any result. Maybe I should override the default behavior of Console.WriteLine or the stringBuilder.ToString() is the problem here?
Here is a screen of what I mean.
And below the code of IdToCode method:
public static string IdToCode(this ulong value)
{
const string charArray = #"1234890qwertyuiopbnmQWERTYUasdfghjklzxcvIOPASDFGHJKLZXCVBNM!+={}[]|\<>?##567$%^&*()-_";
StringBuilder stringBuilder = new StringBuilder();
ulong num = value;
while (num != 0UL)
{
ulong index = num % (ulong)charArray.Length;
num /= (ulong)charArray.Length;
stringBuilder.Insert(0, charArray[(int)index].ToString());
}
return stringBuilder.ToString();
}
I've changed the char array into different one but the general method it's the same as above.
The problem is you need to use the # in front of the string literal which actually adds the backslash to the StringBuilder.
There is no point in doing #id.IdToCode(), because when the string is returned, it already contains (V\|RN. The tooltip shows \\ because it shows the escaped eversion - meaning the single backslash.
One thing that is certain is that the problem can't be resolved here, but only inside the IdToCode method, where it actually originates.
Compare this (same as your code):
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return "(\\VN";
}
Hovering over str I see (\\VN - two backslashes, output is just one backslash - which is correct.
And this:
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return #"(\\VN";
}
Here the tooltip shows "(\\\\VN" which is again correct - there are two actual backslashes and console output is the desired (\\VN

Replace a substring

I have an input string. I need to replace its prefix (until first dot) with an other string.
The method signature:
string MyPrefixReplace(string input, string replacer)
Examples:
string res = MyPrefixReplace("12.345.6789", "000")
res = "000.345.6789";
res = MyPrefixReplace("908.345.6789", "1")
res = "1.345.6789";
Is there a way not to extract a sub-string before first dot and make a Replace**?
I.e - I don't want this solution
int i = input.IndexOf(".");
string rep = input.Substring(0,i);
input.Replace(rep,replacer);
Thanks
You could use String.Split
public string MyPrefixReplace(string source, string value, char delimiter = '.')
{
var parts = source.Split(delimiter);
parts[0] = value;
return String.Join(delimiter.ToString(), parts);
}
Live demo
Using String.IndexOf and String.Substring ist the most efficient way. In your approach you have used the wrong overload of Substring. String.Replace is pointless anyway since you don't want to replace all occurences of the first part but only the first part.
Therefore you don't have to take but to skip the the first part and prefix another. This works as desired:
public static string MyPrefixReplace(string input, string replacer, char prefixChar = '.')
{
int index = input.IndexOf(prefixChar);
if (index == -1)
return input;
return replacer + input.Substring(index);
}
Your input:
string result = MyPrefixReplace("908.345.6789", "1"); // 1.345.6789
result = MyPrefixReplace("12.345.6789", "000"); // 000.345.6789
Personally, I'd split the string up to get around this problem, although there's obviously other ways of doing this, this would be my approach:
string Input = "123.456.789"
string[] SplitInput = Input.Split('.');
SplitInput[0] = "321";
string Output = String.Join('.', SplitInput);
Output should be "321.456.789".

How can I truncate my strings with a "..." if they are too long?

Hope somebody has a good idea. I have strings like this:
abcdefg
abcde
abc
What I need is for them to be trucated to show like this if more than a specified lenght:
abc ..
abc ..
abc
Is there any simple C# code I can use for this?
Here is the logic wrapped up in an extension method:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}
Usage:
var s = "abcdefg";
Console.WriteLine(s.Truncate(3));
All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.
private string TruncateForDisplay(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
var returnValue = value;
if (value.Length > length)
{
var tmp = value.Substring(0, length) ;
if (tmp.LastIndexOf(' ') > 0)
returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
}
return returnValue;
}
public string TruncString(string myStr, int THRESHOLD)
{
if (myStr.Length > THRESHOLD)
return myStr.Substring(0, THRESHOLD) + "...";
return myStr;
}
Ignore the naming convention it's just in case he actually needs the THRESHOLD variable or if it's always the same size.
Alternatively
string res = (myStr.Length > THRESHOLD) ? myStr.Substring(0, THRESHOLD) + ".." : myStr;
Here's a version that accounts for the length of the ellipses:
public static string Truncate(this string value, int maxChars)
{
const string ellipses = "...";
return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
}
There isn't a built in method in the .NET Framework which does this, however this is a very easy method to write yourself. Here are the steps, try making it yourself and let us know what you come up with.
Create a method, perhaps an extension method public static void TruncateWithEllipsis(this string value, int maxLength)
Check to see if the passed in value is greater than the maxLength specified using the Length property. If the value not greater than maxLength, just return the value.
If we didn't return the passed in value as is, then we know we need to truncate. So we need to get a smaller section of the string using the SubString method. That method will return a smaller section of a string based on a specified start and end value. The end position is what was passed in by the maxLength parameter, so use that.
Return the sub section of the string plus the ellipsis.
A great exercise for later would be to update the method and have it break only after full words. You can also create an overload to specify how you would like to show a string has been truncated. For example, the method could return " (click for more)" instead of "..." if your application is set up to show more detail by clicking.
Code behind:
string shorten(sting s)
{
//string s = abcdefg;
int tooLongInt = 3;
if (s.Length > tooLongInt)
return s.Substring(0, tooLongInt) + "..";
return s;
}
Markup:
<td><%= shorten(YOUR_STRING_HERE) %></td>
Maybe it is better to implement a method for that purpose:
string shorten(sting yourStr)
{
//Suppose you have a string yourStr, toView and a constant value
string toView;
const int maxView = 3;
if (yourStr.Length > maxView)
toView = yourStr.Substring(0, maxView) + " ..."; // all you have is to use Substring(int, int) .net method
else
toView = yourStr;
return toView;
}
I found this question after searching for "C# truncate ellipsis". Using various answers, I created my own solution with the following features:
An extension method
Add an ellipsis
Make the ellipsis optional
Validate that the string is not null or empty before attempting to truncate it.
public static class StringExtensions
{
public static string Truncate(this string value,
int maxLength,
bool addEllipsis = false)
{
// Check for valid string before attempting to truncate
if (string.IsNullOrEmpty(value)) return value;
// Proceed with truncating
var result = string.Empty;
if (value.Length > maxLength)
{
result = value.Substring(0, maxLength);
if (addEllipsis) result += "...";
}
else
{
result = value;
}
return result;
}
}
I hope this helps someone else.
string s = "abcdefg";
if (s.length > 3)
{
s = s.substring(0,3);
}
You can use the Substring function.
Refactor with new C# features just for disclosure:
Nullables (C# 7)
Expression-bodied members (C# 6 and 7)
Ranges on strings (C# 8)
// public static class StringExtensions { ...
private static string? Truncate(this string? value, int maxChars)
=>
string.IsNullOrEmpty(value) ? value :
value.Length <= maxChars ? value :
value[..maxChars] + "...";
Checked as "Community wiki", be free to improve answer.
Sure, here is some sample code:
string str = "abcdefg";
if (str.Length > X){
str = str.Substring(0, X) + "...";
}
I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.
But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.
I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...
if (CurrentStatus.Length >= 3750)
{
// perform some truncation to free up some space.
// Lets get the status messages into an array for processing...
// We use the period as the delimiter, then skip the first item and re-insert into an array.
string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
.Skip(1).ToArray();
// Next we return the data to a string and replace any escaped returns with proper one.
CurrentStatus = (string.Join(".", statusArray))
.Replace("\\r\\n", Environment.NewLine);
}
Hope it helps someone out.

How can I parse the int from a String in C#?

I have a string that contains an int. How can I parse the int in C#?
Suppose I have the following strings, which contains an integer:
15 person
person 15
person15
15person
How can I track them, or return null if no integer is found in the string?
You can remove all non-digits, and parse the string if there is anything left:
str = Regex.Replace(str, "\D+", String.Empty);
if (str.Length > 0) {
int value = Int32.Parse(str);
// here you can use the value
}
Paste this code into a test:
public int? ParseAnInt(string s)
{
var match = System.Text.RegularExpressions.Regex.Match(s, #"\d+");
if (match.Success)
{
int result;
//still use TryParse to handle integer overflow
if (int.TryParse(match.Value, out result))
return result;
}
return null;
}
[TestMethod]
public void TestThis()
{
Assert.AreEqual(15, ParseAnInt("15 person"));
Assert.AreEqual(15, ParseAnInt("person 15"));
Assert.AreEqual(15, ParseAnInt("person15"));
Assert.AreEqual(15, ParseAnInt("15person"));
Assert.IsNull(ParseAnInt("nonumber"));
}
The method returns null is no number is found - it also handles the case where the number causes an integer overflow.
To reduce the chance of an overflow you could instead use long.TryParse
Equally if you anticipate multiple groups of digits, and you want to parse each group as a discreet number you could use Regex.Matches - which will return an enumerable of all the matches in the input string.
Use something like this :
Regex r = new Regex("\d+");
Match m = r.Match(yourinputstring);
if(m.Success)
{
Dosomethingwiththevalue(m.Value);
}
Since everyone uses Regex to extract the numbers, here's a Linq way to do it:
string input = "15person";
string numerics = new string(input.Where(Char.IsDigit).ToArray());
int result = int.Parse(numerics);
Just for the sake of completeness, it's probably not overly elegant. Regarding Jaymz' comment, this would return 151314 when 15per13so14n is passed.

Trim last character from a string

I have a string say
"Hello! world!"
I want to do a trim or a remove to take out the ! off world but not off Hello.
"Hello! world!".TrimEnd('!');
read more
EDIT:
What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.
Trim - Removes all occurrences of
white space characters from the
beginning and end of this instance.
MSDN-Trim
Under this definition removing only last character from string is bad solution.
So if we want to "Trim last character from string" we should do something like this
Example as extension method:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string,
but if you want to remove only the last character you should use this :
else { return str.Remove(str.Length - 1); }
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
if (yourString.Length > 1)
withoutLast = yourString.Substring(0, yourString.Length - 1);
or
if (yourString.Length > 1)
withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
...in case you want to remove a non-whitespace character from the end.
The another example of trimming last character from a string:
string outputText = inputText.Remove(inputText.Length - 1, 1);
You can put it into an extension method and prevent it from null string, etc.
Try this:
return( (str).Remove(str.Length-1) );
In .NET 5 / C# 8:
You can write the code marked as the answer as:
public static class StringExtensions
{
public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}
However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
A quick explanation for the new stuff in C# 8:
The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.
string s1 = "Hello! world!";
string s2 = s1.Trim('!');
string helloOriginal = "Hello! World!";
string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
string s1 = "Hello! world!"
string s2 = s1.Substring(0, s1.Length - 1);
Console.WriteLine(s1);
Console.WriteLine(s2);
Very easy and simple:
str = str.Remove( str.Length - 1 );
you could also use this:
public static class Extensions
{
public static string RemovePrefix(this string o, string prefix)
{
if (prefix == null) return o;
return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
}
public static string RemoveSuffix(this string o, string suffix)
{
if(suffix == null) return o;
return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
}
}
An example Extension class to simplify this: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
Usage
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
Slightly modified version of #Damian LeszczyƄski - Vash that will make sure that only a specific character will be removed.
public static class StringExtensions
{
public static string TrimLastCharacter(this string str, char character)
{
if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
{
return str;
}
return str.Substring(0, str.Length - 1);
}
}
I took the path of writing an extension using the TrimEnd just because I was already using it inline and was happy with it...
i.e.:
static class Extensions
{
public static string RemoveLastChars(this String text, string suffix)
{
char[] trailingChars = suffix.ToCharArray();
if (suffix == null) return text;
return text.TrimEnd(trailingChars);
}
}
Make sure you include the namespace in your classes using the static class ;P and usage is:
string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");
If you want to remove the '!' character from a specific expression("world" in your case), then you can use this regular expression
string input = "Hello! world!";
string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
// result: "Hello! world"
the $1 special character contains all the matching "world" expressions, and it is used to replace the original "world!" expression

Categories