how to do substring in reverse mode in c# - 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);

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

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

How to Remove the last char of String in C#?

I have a numeric string, which may be "124322" or "1231.232" or "132123.00".
I want to remove the last char of my string (whatever it is).
So I want if my string is "99234" became "9923".
The length of string is variable. It's not constant so I can not use string.Remove or trim or some like them(I Think).
How do I achieve this?
YourString = YourString.Remove(YourString.Length - 1);
var input = "12342";
var output = input.Substring(0, input.Length - 1);
or
var output = input.Remove(input.Length - 1);
newString = yourString.Substring(0, yourString.length -1);
If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:
public static String TrimEnd(this String str, int count)
{
return str.Substring(0, str.Length - count);
}
and call it:
string oldString = "...Hello!";
string newString = oldString.TrimEnd(1); //returns "...Hello"
or chained:
string newString = oldString.Substring(3).TrimEnd(1); //returns "Hello"
If you are using string datatype, below code works:
string str = str.Remove(str.Length - 1);
But when you have StringBuilder, you have to specify second parameter length as well.
That is,
string newStr = sb.Remove(sb.Length - 1, 1).ToString();
To avoid below error:

Replace consecutive characters with same single character

I was just wondering if there is a simple way of doing this. i.e. Replacing the occurrence of consecutive characters with the same character.
For eg: - if my string is "something likeeeee tttthhiiissss" then my final output should be "something like this".
The string can contain special characters too including space.
Can you guys suggest some simple way for doing this.
This should do it:
var regex = new Regex("(.)\\1+");
var str = "something likeeeee!! tttthhiiissss";
Console.WriteLine(regex.Replace(str, "$1")); // something like! this
The regex will match any character (.) and \\1+ will match whatever was captured in the first group.
string myString = "something likeeeee tttthhiiissss";
char prevChar = '';
StringBuilder sb = new StringBuilder();
foreach (char chr in myString)
{
if (chr != prevChar) {
sb.Append(chr);
prevChar = chr;
}
}
How about:
s = new string(s
.Select((x, i) => new { x, i })
.Where(x => x.i == s.Length - 1 || s[x.i + 1] != x.x)
.Select(x => x.x)
.ToArray());
In english, we are creating a new string based on a char[] array. We construct that char[] array by applying a few LINQ operators:
Select: Capture the index i along with the current character x.
Filter out charaters that are not the same as the subsequent character
Select the character x.x back out of the anonymous type x.
Convert back to a char[] array so we can pass to constructor of string.
Console.WriteLine("Enter any string");
string str1, result="", str = Console.ReadLine();
char [] array= str.ToCharArray();
int i=0;
for (i = 0; i < str.Length;i++ )
{
if ((i != (str.Length - 1)))
{ if (array[i] == array[i + 1])
{
str1 = str.Trim(array[i]);
}
else
{
result += array[i];
}
}
else
{
result += array[i];
}
}
Console.WriteLine(result);
In this code the program ;
will read the string as entered from user
2.Convert the string in char Array using string.ToChar()
The loop will run for each character in string
each character stored in that particular position in array will be compared to the character stored in position one greater than that . And if the characters are found same the character stored in that particular array would be trimmed using .ToTrim()
For last character the loop will show error of index out of bound as it would be the last position value of the array. That's why I used * if ((i != (str.Length - 1)))*
6.The characters left after trimming are stored in result in concatenated form .
word = "something likeeeee tttthhiiissss"
re.sub(r"(.)\1+", r"\1",word)

How do I extract text that lies between parentheses (round brackets)?

I have a string User name (sales) and I want to extract the text between the brackets, how would I do this?
I suspect sub-string but I can't work out how to read until the closing bracket, the length of text will vary.
If you wish to stay away from regular expressions, the simplest way I can think of is:
string input = "User name (sales)";
string output = input.Split('(', ')')[1];
A very simple way to do it is by using regular expressions:
Regex.Match("User name (sales)", #"\(([^)]*)\)").Groups[1].Value
As a response to the (very funny) comment, here's the same Regex with some explanation:
\( # Escaped parenthesis, means "starts with a '(' character"
( # Parentheses in a regex mean "put (capture) the stuff
# in between into the Groups array"
[^)] # Any character that is not a ')' character
* # Zero or more occurrences of the aforementioned "non ')' char"
) # Close the capturing group
\) # "Ends with a ')' character"
Assuming that you only have one pair of parenthesis.
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
Use this function:
public string GetSubstringByString(string a, string b, string c)
{
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
and here is the usage:
GetSubstringByString("(", ")", "User name (sales)")
and the output would be:
sales
Regular expressions might be the best tool here. If you are not famililar with them, I recommend you install Expresso - a great little regex tool.
Something like:
Regex regex = new Regex("\\((?<TextInsideBrackets>\\w+)\\)");
string incomingValue = "Username (sales)";
string insideBrackets = null;
Match match = regex.Match(incomingValue);
if(match.Success)
{
insideBrackets = match.Groups["TextInsideBrackets"].Value;
}
string input = "User name (sales)";
string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
A regex maybe? I think this would work...
\(([a-z]+?)\)
using System;
using System.Text.RegularExpressions;
private IEnumerable<string> GetSubStrings(string input, string start, string end)
{
Regex r = new Regex(Regex.Escape(start) +`"(.*?)"` + Regex.Escape(end));
MatchCollection matches = r.Matches(input);
foreach (Match match in matches)
yield return match.Groups[1].Value;
}
int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);
Use a Regular Expression:
string test = "(test)";
string word = Regex.Match(test, #"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
The regex method is superior I think, but if you wanted to use the humble substring
string input= "my name is (Jayne C)";
int start = input.IndexOf("(");
int stop = input.IndexOf(")");
string output = input.Substring(start+1, stop - start - 1);
or
string input = "my name is (Jayne C)";
string output = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);
var input = "12(34)1(12)(14)234";
var output = "";
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '(')
{
var start = i + 1;
var end = input.IndexOf(')', i + 1);
output += input.Substring(start, end - start) + ",";
}
}
if (output.Length > 0) // remove last comma
output = output.Remove(output.Length - 1);
output : "34,12,14"
Here is a general purpose readable function that avoids using regex:
// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
int iStart = text.IndexOf(start);
iStart = (iStart == -1) ? 0 : iStart + start.Length;
int iEnd = text.LastIndexOf(end);
if(iEnd == -1)
{
iEnd = text.Length;
}
int len = iEnd - iStart;
return text.Substring(iStart, len);
}
To call it in your particular example you can do:
string result = ExtractBetween("User name (sales)", "(", ")");
I'm finding that regular expressions are extremely useful but very difficult to write. So, I did some research and found this tool that makes writing them so easy.
Don't shy away from them because the syntax is difficult to figure out. They can be so powerful.
This code is faster than most solutions here (if not all), packed as String extension method, it does not support recursive nesting:
public static string GetNestedString(this string str, char start, char end)
{
int s = -1;
int i = -1;
while (++i < str.Length)
if (str[i] == start)
{
s = i;
break;
}
int e = -1;
while(++i < str.Length)
if (str[i] == end)
{
e = i;
break;
}
if (e > s)
return str.Substring(s + 1, e - s - 1);
return null;
}
This one is little longer and slower, but it handles recursive nesting more nicely:
public static string GetNestedString(this string str, char start, char end)
{
int s = -1;
int i = -1;
while (++i < str.Length)
if (str[i] == start)
{
s = i;
break;
}
int e = -1;
int depth = 0;
while (++i < str.Length)
if (str[i] == end)
{
e = i;
if (depth == 0)
break;
else
--depth;
}
else if (str[i] == start)
++depth;
if (e > s)
return str.Substring(s + 1, e - s - 1);
return null;
}
I've been using and abusing C#9 recently and I can't help throwing in Spans even in questionable scenarios... Just for the fun of it, here's a variation on the answers above:
var input = "User name (sales)";
var txtSpan = input.AsSpan();
var startPoint = txtSpan.IndexOf('(') + 1;
var length = txtSpan.LastIndexOf(')') - startPoint;
var output = txtSpan.Slice(startPoint, length);
For the OP's specific scenario, it produces the right output.
(Personally, I'd use RegEx, as posted by others. It's easier to get around the more tricky scenarios where the solution above falls apart).
A better version (as extension method) I made for my own project:
//Note: This only captures the first occurrence, but
//can be easily modified to scan across the text (I'd prefer Slicing a Span)
public static string ExtractFromBetweenChars(this string txt, char openChar, char closeChar)
{
ReadOnlySpan<char> span = txt.AsSpan();
int firstCharPos = span.IndexOf(openChar);
int lastCharPos = -1;
if (firstCharPos != -1)
{
for (int n = firstCharPos + 1; n < span.Length; n++)
{
if (span[n] == openChar) firstCharPos = n; //This allows the opening char position to change
if (span[n] == closeChar) lastCharPos = n;
if (lastCharPos > firstCharPos) break;
//This would correctly extract "sales" from this [contrived]
//example: "just (a (name (sales) )))(test"
}
return span.Slice(firstCharPos + 1, lastCharPos - firstCharPos - 1).ToString();
}
return "";
}
Much similar to #Gustavo Baiocchi Costa but offset is being calculated with another intermediate Substring.
int innerTextStart = input.IndexOf("(") + 1;
int innerTextLength = input.Substring(start).IndexOf(")");
string output = input.Substring(innerTextStart, innerTextLength);
I came across this while I was looking for a solution to a very similar implementation.
Here is a snippet from my actual code. Starts substring from the first char (index 0).
string separator = "\n"; //line terminator
string output;
string input= "HowAreYou?\nLets go there!";
output = input.Substring(0, input.IndexOf(separator));

Categories