Left function in c# [duplicate] - c#

This question already has answers here:
.NET equivalent of the old vb left(string, length) function
(11 answers)
Closed 3 years ago.
what is the alternative for Left function in c#
i have this in
Left(fac.GetCachedValue("Auto Print Clinical Warnings").ToLower + " ", 1) == "y");

It sounds like you're asking about a function
string Left(string s, int left)
that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:
public static class StringExtensions
{
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return ( value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}
and use it like so:
string left = s.Left(number);
For your specific example:
string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);

It's the Substring method of String, with the first argument set to 0.
myString.Substring(0,1);
[The following was added by Almo; see Justin J Stark's comment. —Peter O.]
Warning:
If the string's length is less than the number of characters you're taking, you'll get an ArgumentOutOfRangeException.

Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.

use substring function:
yourString.Substring(0, length);

var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
// Do your stuff.
}

Related

how to censor the first 10 char in a string using c#

so I want to create a credit card encoder (if this even a word) that takes a string and put the first 10 digits of the string as '*'
this is the code I came up with:
public static string[] ToCencoredString(this string str)
{
char[] array = Enumerable.Repeat('*', str.Length-1).ToArray();
array = array.Select((cha, index) =>
{
if (index < 10)
array[index] = str[index];
});
}
(ignoringe the fact the function returns string[] there is another part of the code which is not relevant)
I don't know why, but I keep getting ArgumentNullException which is odd because there is not a single value in array witch is null.
what am I doing wrong?
What about changing it to something a bit more simple:
var result = string.Concat(Enumerable.Repeat("*", 10)) + str.Substring(10);
I'd use this more efficient version using String.Substring and the string constructor:
public static string ToCencoredString(this string str, int length = 10)
{
if (String.IsNullOrEmpty(str)) return str;
string censored = new string('*', length);
if (str.Length <= length) return censored;
return censored + str.Substring(length);
}
I suggest you use the original array for iterating so that you can make use of its index to create the mask. A String.Join() may help you to produce the masked output. The code would be something like this:
string maskedInput = String.Join("", str.Select((c, index) => index < 10? '*' : c));
Here is a working example for your reference
Your code doesn't compile. So I dont know how you managed to reach ArgumentNullException.
And that's not how you use LINQ. The correct way (although not a good way, since the answers above are apparently way better) to implement what's in your mind
array = array.Select((cha, index) =>
{
if (index < 10)
return array[index];
else
return str[index];
}).ToArray();
$"{string.Concat(Enumerable.Repeat("*", 10))}{FIELD.Substring(10)}";

How do you pad a string with a given character or make it empty if length to pad is 0 in C#?

Is there a function that does almost exactly what String.PadLeft(int length) does except that if length is 0 make the string empty?
This is what I want to do:
string someText = "abc".PadLeft(8, '0');
Console.WriteLine(someText);
string otherText = "xyz".PadLeft(0, '0');
Console.WriteLine(otherText);
Console.WriteLine("Done!");
I want the output to be this:
00000abc
Done!
However, the actual output is this:
00000abc
xyz
Done!
There's no such method. However, you can write your own Extension Method that does what you want.
This method behaves exactly like the classic PadLeft, except it returns an empty string if the provided length is 0.
You can easily change the condition from padLength == 0 to padLength < input.Length if you wish to return an empty string if the padding is lower than the string's length.
public static class Extensions
{
public static string CustomPadLeft(this string input, int padLength, char padChar)
{
if (padLength == 0)
{
return string.Empty;
}
return input.PadLeft(padLength, padChar);
}
}
Here's the corresponding unit test to validate the behavior:
[TestMethod]
public void PadTest()
{
Assert.AreEqual(string.Empty, "xyz".CustomPadLeft(0, '0'));
Assert.AreEqual("xyz", "xyz".CustomPadLeft(2, '0'));
Assert.AreEqual("00000abc", "abc".CustomPadLeft(8, '0'));
}
I also suggest you find a better name than my CustomPadLeft...

How to find a pair of chars within a string in c# netMF?

This has probably (somewhere) been asked before, but can't find any documentation on it (i have looked!).
Say I had declared a string like:
String Test = "abcdefg";
How would i go about searching the string to see if I could see "cd" anywhere in the string by searching through the string in pairs, like:
{ab}{bc}{cd}{de}{ef}{fg}
That is, if I split each of the values up, and searched for a pair of chars next to each other? Is there a built in function for this?
I have thought about using a char array for this, but it seems to (logically) be very 'heavy'/'slow'. Would there be a better solution to search this string?
EDIT 1
Once I see this "cd", I would then need to doSomething() at that position (which I have already implemented by using the substring method.
Try this.
String.IndexOf(...) != -1
For more infö, read here.
Similar to the answer from Neo, but in a loop to get all instances within the string:
string Test = "abcdefgcd";
int index = Test.IndexOf("cd");
while (index > -1)
{
//DoSomething();
index = Test.IndexOf("cd", ++index);
}
The first IndexOf checks for the existence of what you want, whilst the second IndexOf (in the loop) checks for a match after the last index.
In the above we find two matches and then the loop ends.
There is no build in function that will do that.
having a for loop should do what you want.
something like that:
string str = string.empty;
for (i=0;i<ch.length;i++) {
if (i != ch.length) {
str += ch[i] + ch[i+1];
}
}
also you can use regex however that wont be fast either.
In order to optimize this on a large scale you can implement byte shifting.
The ASCII code of your string characters is your friend in this case, full working example below:
var yourString = "abcdefg";
var x = '\0';
for (var i = 0; i < yourString.Length; i++)
{
//check whether i+1 index is not out of range
if (i + 1 != yourString.Length)
{
var test = yourString[i + 1];
x = yourString[i];
if(x.ToString() + test.ToString() == "cd")
{
Console.Write("Found at position " + i)
}
}
}

VB6 to C#: Loop or Index Issue?

I have an old VB6 project that I am converting to C#. I have a string. I am verifying, 1 character at a time, that it only contains [E0-9.+-].
This is the old VB6 code:
sepIndex = 1
Do While Mid(xyString, sepIndex, 1) Like "[E0-9.+-]"
sepIndex = sepIndex + 1
Loop
I am then using the index number to calculate the Left of the same string, and convert it to a double. Using Right, I then cut the string down to the remaining part of the string that I want:
xFinal = CDbl(left(xyString, sepIndex - 1))
xyString = LTrim(right(xyString, Len(xyString) - sepIndex + 1))
This works great in VB, and I have no problems whatsoever. In C# it is different. Knowing that the only way to emulate Left/Mid/Right in C# is to create my own function, I did so (part of my Utils namespace):
public static string Mid(string param, int startIndex)
{
try
{
//start at the specified index and return all characters after it
//and assign it to a variable
string result = param.Substring(startIndex);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
public static string Right(string param, int length)
{
try
{
//start at the index based on the lenght of the sting minus
//the specified lenght and assign it a variable
string result = param.Substring(param.Length - length, length);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
public static string Left(string param, int length)
{
try
{
//we start at 0 since we want to get the characters starting from the
//left and with the specified lenght and assign it to a variable
string result = param.Substring(0, length);
//return the result of the operation
return result;
}
catch
{
return string.Empty;
}
}
To the best of my knowledge, I have converted the code from VB6 to C#. The problem is that when it finally sets xyString, it is cutting the string in the wrong spot, and still leaving a trailing character that I want in xFinal.
From what I gather, this may be either an index issue (which I know in C#, Substring is 0-based, so I changed sepIndex to the value of 0), or problem with the wrong loop structure.
Here is the converted code, and I hope I could get some idea of what is going on here:
sepIndex = 0;
while (Regex.IsMatch(Utils.Mid(xyString, sepIndex, 1), "[E0-9.+-]"))
{
sepIndex++;
}
xFinal = Convert.ToDouble(Utils.Left(xyString, sepIndex - 1)); // - 1
xyString = Utils.Right(xyString, xyString.Length - sepIndex + 1).TrimStart(' '); // + 1
EDIT
This has been solved. I simply removed the +1 and -1 from my Utils.Left function, and it returned the proper string. Thanks for the inputs.
Seems to be just RegEx math with negative condition - "[^E0-9.+-]":
var sepIndex = Regex.Match(xyString, #"[^E0-9\.+-]+").Index;
If you need to do it by hand the easiest way to get single character is to just get single character from the string without trimming:
// replace Utils.Mid(xyString, sepIndex, 1) with
xyString[sepIndex]
Try using following
do{
sepIndex++;
}while (Regex.IsMatch(Utils.Mid(xyString, sepIndex, 1), "[E0-9.+-]"))
why not importing microsoft.visualbasic namespace?
class Program
{
static void Main(string[] args)
{
string t = Microsoft.VisualBasic.Strings.Mid("hello", 2);
}
}
you can reuse what you had before

How do I get the last four characters from a string in C#?

Suppose I have a string:
"34234234d124"
I want to get the last four characters of this string which is "d124". I can use SubString, but it needs a couple of lines of code, including naming a variable.
Is it possible to get this result in one expression with C#?
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?
If you're positive the length of your string is at least 4, then it's even shorter:
mystring.Substring(mystring.Length - 4);
You can use an extension method:
public static class StringExtension
{
public static string GetLast(this string source, int tail_length)
{
if(tail_length >= source.Length)
return source;
return source.Substring(source.Length - tail_length);
}
}
And then call:
string mystring = "34234234d124";
string res = mystring.GetLast(4);
Update 2020: C# 8.0 finally makes this easy:
> "C# 8.0 finally makes this easy"[^4..]
"easy"
You can also slice arrays in the same way, see Indices and ranges.
All you have to do is..
String result = mystring.Substring(mystring.Length - 4);
Ok, so I see this is an old post, but why are we rewriting code that is already provided in the framework?
I would suggest that you add a reference to the framework DLL "Microsoft.VisualBasic"
using Microsoft.VisualBasic;
//...
string value = Strings.Right("34234234d124", 4);
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)
Using Substring is actually quite short and readable:
var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
// result == "d124"
Here is another alternative that shouldn't perform too badly (because of deferred execution):
new string(mystring.Reverse().Take(4).Reverse().ToArray());
Although an extension method for the purpose mystring.Last(4) is clearly the cleanest solution, albeit a bit more work.
You can simply use Substring method of C#. For ex.
string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);
It will return result 0000.
A simple solution would be:
string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);
Definition:
public static string GetLast(string source, int last)
{
return last >= source.Length ? source : source.Substring(source.Length - last);
}
Usage:
GetLast("string of", 2);
Result:
of
string var = "12345678";
var = var[^4..];
// var = "5678"
This is index operator that literally means "take last four chars from end (^4) until the end (..)"
mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;
Compared to some previous answers, the main difference is that this piece of code takes into consideration when the input string is:
Null
Longer than or matching the requested length
Shorter than the requested length.
Here it is:
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
public static string MyLast(this string str, int length)
{
if (str == null)
return null;
else if (str.Length >= length)
return str.Substring(str.Length - length, length);
else
return str;
}
}
It is just this:
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
I would like to extend the existing answer mentioning using new ranges in C# 8 or higher: To make the code usable for all possible strings, even those shorter than 4, there is some form of condition needed! If you want to copy code, I suggest example 5 or 6.
string mystring ="C# 8.0 finally makes slicing possible";
1: Slicing taking the end part- by specifying how many characters to omit from the beginning- this is, what VS 2019 suggests:
string example1 = mystring[Math.Max(0, mystring.Length - 4)..] ;
2: Slicing taking the end part- by specifying how many characters to take from the end:
string example2 = mystring[^Math.Min(mystring.Length, 4)..] ;
3: Slicing taking the end part- by replacing Max/Min with the ?: operator:
string example3 = (mystring.length > 4)? mystring[^4..] : mystring);
Personally, I like the second and third variant more than the first.
MS doc reference for Indices and ranges:
Null? But we are not done yet concerning universality. Every example so far will throw an exception for null strings. To consider null (if you don´t use non-nullable strings with C# 8 or higher), and to do it without 'if' (classic example 'with if' already given in another answer) we need:
4: Slicing considering null- by specifying how many characters to omit:
string example4 = mystring?[Math.Max(0, mystring.Length - 4)..] ?? string.Empty;
5: Slicing considering null- by specifying how many characters to take:
string example5 = mystring?[^Math.Min(mystring.Length, 4)..] ?? string.Empty;
6: Slicing considering null with the ?: operator (and two other '?' operators ;-) :
(You cannot put that in a whole in a string interpolation e.g. for WriteLine.)
string example6 = (mystring?.Length > 4) ? filePath[^4..] : mystring ?? string.Empty;
7: Equivalent variant with good old Substring() for C# 6 or 7.x:
(You cannot put that in a whole in a string interpolation e.g. for WriteLine.)
string example7 = (mystring?.Length > 4) ? mystring.Substring(mystring.Length- 4) : mystring ?? string.Empty;
Graceful degradation?
I like the new features of C#. Putting them on one line like in the last examples maybe looks a bit excessive. We ended up a little perl´ish didn´t we?
But it´s a good example for learning and ok for me to use it once in a tested library method.
Even better that we can get rid of null in modern C# if we want and avoid all this null-specific handling.
Such a library/extension method as a shortcut is really useful. Despite the advances in C# you have to write your own to get something easier to use than repeating the code above for every small string manipulation need.
I am one of those who began with BASIC, and 40 years ago there was already Right$(,). Funny, that it is possible to use Strings.Right(,) from VB with C# still too as was shown in another answer.
C# has chosen precision over graceful degradation (in opposite to old BASIC).
So copy any appropriate variant you like in these answers and define a graceful shortcut function for yourself, mine is an extension function called RightChars(int).
This works nice, as there are no errors if there are less characters in the string than the requested amount.
using System.Linq;
string.Concat("123".TakeLast(4));
This won't fail for any length string.
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
This is probably overkill for the task at hand, but if there needs to be additional validation, it can possibly be added to the regular expression.
Edit: I think this regex would be more efficient:
#".{4}\Z"
Using the range operator is the easiest way for me. No many codes is required.
In your case, you can get what you want like this:
// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]
string x = "34234234d124";
string y = x.Substring(x.Length - 4);
Use a generic Last<T>. That will work with ANY IEnumerable, including string.
public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
int count = Math.Min(enumerable.Count(), nLastElements);
for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
{
yield return enumerable.ElementAt(i);
}
}
And a specific one for string:
public static string Right(this string str, int nLastElements)
{
return new string(str.Last(nLastElements).ToArray());
}
Suggest using TakeLast method, for example: new String(text.TakeLast(4).ToArray())
I threw together some code modified from various sources that will get the results you want, and do a lot more besides. I've allowed for negative int values, int values that exceed the length of the string, and for end index being less than the start index. In that last case, the method returns a reverse-order substring. There are plenty of comments, but let me know if anything is unclear or just crazy. I was playing around with this to see what all I might use it for.
/// <summary>
/// Returns characters slices from string between two indexes.
///
/// If start or end are negative, their indexes will be calculated counting
/// back from the end of the source string.
/// If the end param is less than the start param, the Slice will return a
/// substring in reverse order.
///
/// <param name="source">String the extension method will operate upon.</param>
/// <param name="startIndex">Starting index, may be negative.</param>
/// <param name="endIndex">Ending index, may be negative).</param>
/// </summary>
public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
{
// If startIndex or endIndex exceeds the length of the string they will be set
// to zero if negative, or source.Length if positive.
if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;
// Negative values count back from the end of the source string.
if (startIndex < 0) startIndex = source.Length + startIndex;
if (endIndex < 0) endIndex = source.Length + endIndex;
// Calculate length of characters to slice from string.
int length = Math.Abs(endIndex - startIndex);
// If the endIndex is less than the startIndex, return a reversed substring.
if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();
return source.Substring(startIndex, length);
}
/// <summary>
/// Reverses character order in a string.
/// </summary>
/// <param name="source"></param>
/// <returns>string</returns>
public static string Reverse(this string source)
{
char[] charArray = source.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
/// <summary>
/// Verifies that the index is within the range of the string source.
/// </summary>
/// <param name="source"></param>
/// <param name="index"></param>
/// <returns>bool</returns>
public static bool ExceedsLength(this string source, int index)
{
return Math.Abs(index) > source.Length ? true : false;
}
So if you have a string like "This is an extension method", here are some examples and results to expect.
var s = "This is an extension method";
// If you want to slice off end characters, just supply a negative startIndex value
// but no endIndex value (or an endIndex value >= to the source string length).
Console.WriteLine(s.Slice(-5));
// Returns "ethod".
Console.WriteLine(s.Slice(-5, 10));
// Results in a startIndex of 22 (counting 5 back from the end).
// Since that is greater than the endIndex of 10, the result is reversed.
// Returns "m noisnetxe"
Console.WriteLine(s.Slice(2, 15));
// Returns "is is an exte"
Hopefully this version is helpful to someone. It operates just like normal if you don't use any negative numbers, and provides defaults for out of range params.
string var = "12345678";
if (var.Length >= 4)
{
var = var.substring(var.Length - 4, 4)
}
// result = "5678"
assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.
Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"
In the above, I need to extract the "273" that I will use in database query
//find the length of the string
int streamLen=StreamSelected.Length;
//now remove all characters except the last 10 characters
string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));
//extract the 3 characters using substring starting from index 0
//show Result is a TextBox (txtStreamSubs) with
txtStreamSubs.Text = streamLessTen.Substring(0, 3);
public static string Last(this string source, int tailLength)
{
return tailLength >= source.Length ? source : source[^tailLength..];
}
This is a bit more than the OP question, but is an example of how to use the last 3 of a string for a specific purpose. In my case, I wanted to do a numerical sort (LINQ OrderBy) on a number field that is stored as a string (1 to 3 digit numbers.) So, to get the string numbers to sort like numeric numbers, I need to left-pad the string numbers with zeros and then take the last 3. The resulting OrderBy statement is:
myList = myList.OrderBy(x => string.Concat("00",x.Id)[^3..])
The string.Concat() used in the OrderBy statement results in strings like "001", "002", "011", "021", "114" which sort the way they would if they were stored as numbers.

Categories

Resources