ASP.Net - Masked first 6 character on a string with dynamic length - c#

is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?
Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.

Yes, it's possible, and even quite easy, using simple string concatenation and SubString:
var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;
If you want shorter strings to mask all characters but keep original length, you can do it like this:
var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;
This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")

Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):
using System.Linq;
...
string original = "Some string here";
string result = "******" + string.Concat(original.Skip(6));
If you want to preserve the length of short (less than 6 character string):
// if original shorter than 6 symbols, e.g. "short"
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong"
// we'll get "******ong" as usual
string original = "short";
...
string result = new string('*', Math.Min(6, original.Length)) +
string.Concat(original.Skip(Math.Min(6, original.Length)));
You may want to have the routine as an extension method:
public static partial class StringExtensions {
public static string MaskPrefix(this string value, int count = 6) {
if (null == value)
throw new ArgumentNullException("value"); // or return value
else if (count < 0)
throw new ArgumentOutOfRangeException("count"); // or return value
int length = Math.Min(value.Length, count);
return new string('*', length) + string.Concat(value.Skip(length));
}
}
And so you can put as if string has MaskPrefix method:
string original = "Some string here";
string result = original.MaskPrefix(6);

You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample
string str = "123456789345798";
var strResult = "******"+str.Substring(6, str.Length - 6);
Console.WriteLine("strResult :" + strResult);

Related

how i can get the string after specific character in my case :?

str="Brand : TROLLBEADS";
int length = str.Length;
length = length - 6;
str = str.Substring(6, length);
i want to display "TROLLBEADS"
and want to discard other remaining string
You can split the string using : delimiter if it is fixed
var result = str.Split(':')[1].Trim();
or if your string can have multiple : in that case
var result = str.Substring(str.IndexOf(":") + 1).Trim();
Split is nice, but a bit too much. You can just specify the start position for substring.
string str="Brand : TROLLBEADS";
string val = str.Substring(str.IndexOf(":") + 1);
Console.WriteLine(val);

how to do substring in reverse mode in c#

My string is "csm15+abc-indiaurban#v2". I want only "indiaurban" from my string. what I am doing right now is :
var lastindexofplusminus = input.LastIndexOfAny(new char[]{'+','-'});
var lastindexofattherate = input.LastIndexOf('#');
string sub = input.Substring(lastindexofplusminus,lastindexofattherate);
but getting error "Index and length must refer to a location within the string."
Thanks in Advance.
You should put the length in the second argument (instead of passing another index) of the Substring you want to grab. Given that you know the two indexes, the translation to the length is pretty straight forward:
string sub = input.Substring(lastindexofplusminus + 1, lastindexofattherate - lastindexofplusminus - 1);
Note, +1 is needed to get the char after your lastindexofplusminus.
-1 is needed to get the Substring between them minus the lastindexofattherate itself.
You can simple reverse the string, apply substring based on position and length, than reverse again.
string result = string.Join("", string.Join("", teste.Reverse()).Substring(1, 10).Reverse());
Or create a function:
public static string SubstringReverse(string str, int reverseIndex, int length) {
return string.Join("", str.Reverse().Skip(reverseIndex - 1).Take(length));
}
View function working here!!
You can use LINQ:
string input = "csm15+abc-indiaurban#v2";
string result = String.Join("", input.Reverse()
.SkipWhile(c => c != '#')
.Skip(1)
.TakeWhile(c => c != '+' && c != '-')
.Reverse());
Console.WriteLine(result); // indiaurban
I don't know what is identify your break point but here is sample which is working
you can learn more about this at String.Substring Method (Int32, Int32)
String s = "csm15+abc-indiaurban#v2";
Char charRange = '-';
Char charEnd = '#';
int startIndex = s.IndexOf(charRange);
int endIndex = s.LastIndexOf(charEnd);
int length = endIndex - startIndex - 1;
Label1.Text = s.Substring(startIndex+1, length);
Assuming that your string is always in that format
string str = "csm15+abc-indiaurban#v2";
string subSTr = str.Substring(10).Substring(0,10);

Substring from specific sign to sign

I have a list of strings in format like this:
Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp
I need only the part from comma sign to the first dot sign.
For example above it should return this string: IScadaManualOverrideService
Anyone has an idea how can I do this and get substrings if I have list of strings like first one?
from comma sign to the first dot sign
You mean from dot to comma?
You can split the string by comma first, then split by dot and take the last:
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.
So here is another one
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', end) + 1;
var result = text.Substring(start, end - start);
Proof woof woof.
Bullet-proof version (ugly)
string text = "IScadaManualOverrideService";
//string text = "Services.IScadaManualOverrideService";
//string text = "IScadaManualOverrideService,";
//string text = "";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
var result = text.Substring(start, (end == -1 ? text.Length : end) - start);
Insert this if hacker attack is expected
if(text == null)
return "Stupid hacker, die!";
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string s1 = s.Substring(0, s.IndexOf(","));
string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
int commaIndex = input.IndexOf(',');
string remainder = input.Substring(0, commaIndex);
int dotIndex = remainder.LastIndexOf('.');
string output = remainder.Substring(dotIndex + 1);
This can be written a lot shorter, but for the explanation i think this is more clear
sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last); // output: IScadaManualOverrideService

Get all instances of sub-string one at a time?

If i have a string containing three 0 values, how would i grab them one by one in order to replace them?
the 0's could be located anywhere in the string.
i don't want to use regex.
example string to parse:
String myString = "hello 0 goodbye 0 clowns are cool 0";
right now i can only find the three 0 values if they are right next to each other. i replace them using stringToParse.Replace("0", "whatever value i want to replace it with");
I want to be able to replace each instance of 0 with a different value...
You can do something like this:
var strings = myString.Split('0');
var replaced = new StringBuilder(strings[0]);
for (var i = 1; i < strings.Length; ++i)
{
replaced.Append("REPLACED " + i.ToString());
replaced.Append(strings[i]);
}
pseudolang :
s = "yes 0 ok 0 and 0"
arr = s.split(" 0")
newstring = arr[0] + replace1 + arr[1] + replace2 + arr[2] + replace3
If you have control of these input strings, then I would use a composite format string instead:
string myString = "hello {0} goodbye {1} clowns are cool {2}";
string replaced = string.Format(myString, "replace0", "replace1", "replace2");
public string ReplaceOne(string full, string match, string replace)
{
int firstMatch = full.indexOf(match);
if(firstMatch < 0)
{
return full;
}
string left;
string right;
if(firstMatch == 0)
left = "";
else
left = full.substring(0,firstMatch);
if(firstMatch + match.length >= full.length)
right = "";
else
right = full.substring(firstMatch+match.length);
return left + replace + right
}
If your match can occur in replace, then you will want to track what index your upto and pass it in to indexOf.
Using LINQ and generic function to decouple replacement logic.
var replace = (index) => {
// put any custom logic here
return (char) index;
};
string input = "hello 0 goodbye 0 clowns are cool 0";
string output = new string(input.Select((c, i) => c == '0' ? replace(i) : c)
.ToArray());
Pros:
Char replacement logic decoupled from the string processing (actually LINQ query)
Cons:
Not the best solution from performance perspectives

How to get the last five characters of a string using Substring() in C#?

I can get the first three characters with the function below.
However, how can I get the output of the last five characters ("Three") with the Substring() function? Or will another string function have to be used?
static void Main()
{
string input = "OneTwoThree";
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
}
If your input string could be less than five characters long then you should be aware that string.Substring will throw an ArgumentOutOfRangeException if the startIndex argument is negative.
To solve this potential problem you can use the following code:
string sub = input.Substring(Math.Max(0, input.Length - 5));
Or more explicitly:
public static string Right(string input, int length)
{
if (length >= input.Length)
{
return input;
}
else
{
return input.Substring(input.Length - length);
}
}
string sub = input.Substring(input.Length - 5);
If you can use extension methods, this will do it in a safe way regardless of string length:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:
string sub = input.Right(5);
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3) - Returns substring of first 3 chars. //One
Substring(3, 3) - Returns substring of second 3 chars. //Two
Substring(6) - Returns substring of all chars after first 6. //Three
One way is to use the Length property of the string as part of the input to Substring:
string sub = input.Substring(input.Length - 5); // Retrieves the last 5 characters of input
Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions to the code file you are using the extension in.
Then you could call:
input.SubstringReverse(-5) and it will return "Three".
namespace AssemblyName.Extensions {
public static class StringExtensions
{
/// <summary>
/// Takes a negative integer - counts back from the end of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
public static string SubstringReverse(this string str, int length)
{
if (length > 0)
{
throw new ArgumentOutOfRangeException("Length must be less than zero.");
}
if (str.Length < Math.Abs(length))
{
throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
}
return str.Substring((str.Length + length), Math.Abs(length));
}
}
}
Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.
See a small example :
string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);
Output :
Substring: One
simple way to do this in one line of code would be this
string sub = input.Substring(input.Length > 5 ? input.Length - 5 : 0);
and here some informations about Operator ? :
string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}
e.g.
string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);
This return "substring"
C# substring sample source
In C# 8.0 and later you can use [^5..] to get the last five characters combined with a ? operator to avoid a potential ArgumentOutOfRangeException.
string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123
index-from-end-operator and range-operator
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

Categories