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

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);

Related

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

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);

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 Remove Last digit of String in .Net?

I want to eliminate B if i scan Serial number bar code: 21524116476CA2006765B
Output: 21524116476CA2006765
string foo = "21524116476CA2006765B";
string bar = foo.Substring(0, Math.Max(foo.Length - 1, 0));
If you can't be certain that the input barcode will always end with a B, do something like this:
char[] barcodeEnd = { 'B' };
string input = "21524116476CA2006765B";
string output = input.TrimEnd(barcodeEnd);
PUt the first line somewhere it'll only get run once, so you aren't constantly creating new char[] arrays. You can add more characters to the array if you're looking for other specific characters.
string s = "21524116476CA2006765B";
string b = s.Substring(0, s.Length - 1);
string value= "21524116476CA2006765B";
string bar = value.Substring(0, 19);
string str = "Your String Whatever it is";
str = str.Substring(0, s.Length - 1);

Categories