What is the most elegant way to implement GetTextAfterMarker() - c#

Here is another old function I have from my C# 1 days, what would be a more elegant way to write it:
//method: gets the text in a string in front of a marker, if marker is not there, then return empty string
//example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "documents"
//example: GetTextAfterMarker("letter043.doc","/") returns ""
//rank:8
public static string GetTextAfterMarker(string line, string marker) {
string r = "";
int pos = line.IndexOf(marker);
if(pos != -1) {
r = line.Substring(pos+(marker.Length),line.Length-pos-(marker.Length));
} else {
r = "";
}
return r;
}

I find the name somewhat strange, given that it should return the text appearing before the first marker. But this one does the same job, I think (I took the liberty to change the name):
public static string GetTextBeforeMarker(string line, string marker)
{
if (line == null)
{
throw new ArgumentNullException("line");
}
if (marker == null)
{
throw new ArgumentNullException("marker");
}
string result = line.Split(new string[] { marker }, StringSplitOptions.None)[0];
return line.Equals(result) ? string.Empty : result;
}
Explanation: split the string into an array using the marker as split argument. If the first element of the result is the same as the input, the marker was not in the string, so we return an empty string, otherwise we return the first element (which is the text up to the first occurrence of the marker).

Am I missing something? Wouldn't this be more simple? Also I prefer Substring to Split.
public static string GetTextAfterMarker(string line, string marker) {
int pos = line.IndexOf(marker);
if (pos == -1)
return string.Empty;
return line.Substring(0,pos);
}

public static string GetTextBeforeMarker(string line, string marker) {
return GetTextAfterMarker(string line, string marker);
}

You could use regular expressions:
public static string GetTextBeforeMarker(string line, string marker)
{
if (String.IsNullOrEmpty(line))
throw new ArgumentException("line is null or empty.", "line");
if (String.IsNullOrEmpty(marker))
throw new ArgumentException("marker is null or empty.", "marker");
string EscapedMarker = Regex.Escape(marker);
return Regex.Match(line, "([^" + EscapedMarker + "]+)" + EscapedMarker).Groups[1].Value;
}

Related

How to remove all characters from a string before a specific character

Suppose I have a string A, for example:
string A = "Hello_World";
I want to remove all characters up to (and including) the _. The exact number of characters before the _ may vary. In the above example, A == "World" after removal.
string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
You have already received a perfectly fine answer. If you are willing to go one step further, you could wrap up the a.SubString(a.IndexOf('_') + 1) in a robust and flexible extension method:
public static string TrimStartUpToAndIncluding(this string str, char ch)
{
if (str == null) throw new ArgumentNullException("str");
int pos = str.IndexOf(ch);
if (pos >= 0)
{
return str.Substring(pos + 1);
}
else // the given character does not occur in the string
{
return str; // there is nothing to trim; alternatively, return `string.Empty`
}
}
which you would use like this:
"Hello_World".TrimStartUpToAndIncluding('_') == "World"
string a = "Hello_World";
a = a.Substring(a.IndexOf("_")+1);
try this? or is the A= part in your A=Hello_World included?
var foo = str.Substring(str.IndexOf('_') + 1);
string orgStr = "Hello_World";
string newStr = orgStr.Substring(orgStr.IndexOf('_') + 1);
you can do this by creating a substring.
simple exampe is here:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("I need this words removed taken please", "taken");

Remove a defined part from a string

Lets say I have this string:
string text = "Hi my name is <crazy> Bob";
I want to take away everything within the brackets so it turns out like this:
"Hi my name is Bob".
So for I've tried with this and I know I've been think wrong with the while-loop but I just can't figure it out.
public static string Remove(string text)
{
char[] result = new char[text.Length];
for (int i = 0; i < text.Length; i++ )
{
if (text[i] == '<')
{
while (text[i] != '>')
{
result[i] += text[i];
}
}
else
{
result[i] += text[i];
}
}
return result.ToString();
}
Try this Regex:
public static string Remove(string text)
{
return Regex.Replace(text, "<.*?>","");
}
Look at this loop:
while (text[i] != '>')
{
result[i] += text[i];
}
That will continue executing until the condition isn't met. Given that you're not changing text[i], it's never going to stop...
Additionally, you're calling ToString on a char[] which isn't going to do what you want, and even if it did you'd have left-over characters.
If you wanted to loop like this, I'd use a StringBuilder, and just keep track of whether you're "in" an angle bracket or not:
public static string RemoveAngleBracketedContent(string text)
{
var builder = new StringBuilder();
int depth = 0;
foreach (var character in text)
{
if (character == '<')
{
depth++;
}
else if (character == '>' && depth > 0)
{
depth--;
}
else if (depth == 0)
{
builder.Append(character);
}
}
return builder.ToString();
}
Alternatively, use a regular expression. It would be relatively tricky to get it to cope with nested angle brackets, but if you don't need that, it's really simple:
// You can reuse this every time
private static Regex AngleBracketPattern = new Regex("<[^>]*>");
...
text = AngleBracketPattern.Replace(text, "");
One last problem though - after removing the angle-bracketed-text from "Hi my name is <crazy> Bob" you actually get "Hi my name is Bob" - note the double space.
use
string text = "Hi my name is <crazy> Bob";
text = System.Text.RegularExpressions.Regex.Replace(text, "<.*?>",string.Empty);
I recommend regex.
public static string DoIt(string content, string from, string to)
{
string regex = $"(\\{from})(.*)(\\{to})";
return Regex.Replace(content, regex, "");
}

First Character of String Lowercase - C# [duplicate]

This question already has answers here:
BestPractice - Transform first character of a string into lower case
(13 answers)
Closed 9 years ago.
How can I make the first character of a string lowercase?
For example: ConfigService
And I need it to be like this: configService
This will work:
public static string? FirstCharToLowerCase(this string? str)
{
if ( !string.IsNullOrEmpty(str) && char.IsUpper(str[0]))
return str.Length == 1 ? char.ToLower(str[0]).ToString() : char.ToLower(str[0]) + str[1..];
return str;
}
(This code arranged as "C# Extension method")
Usage:
myString = myString.FirstCharToLowerCase();
One way:
string newString = oldString;
if (!String.IsNullOrEmpty(newString))
newString = Char.ToLower(newString[0]) + newString.Substring(1);
For what it's worth, an extension method:
public static string ToLowerFirstChar(this string input)
{
if(string.IsNullOrEmpty(input))
return input;
return char.ToLower(input[0]) + input.Substring(1);
}
Usage:
string newString = "ConfigService".ToLowerFirstChar(); // configService
You could try this:
lower = source.Substring(0, 1).ToLower() + source.Substring(1);
string FirstLower(string s)
{
if(string.IsNullOrEmpty(s))
return s;
return s[0].ToString().ToLower() + s.Substring(1);
}
Use this function:
public string GetStringWithFirstCharLowerCase(string value)
{
if (value == null) throw new ArgumentNullException("value")
if (String.IsNullOrWhiteSpace(value)) return value;
char firstChar = Char.ToLowerInvariant(value[0]);
if (value.Length == 1) return firstChar;
return firstChar + value.Substring(1);
}
Please note that further overloading will be necessary if support for other languages is required.
public static string Upper_To_Lower(string text)
{
if (Char.IsUpper(text[0]) == true) { text = text.Replace(text[0], char.ToLower(text[0])); return text; }
return text;
}
public static string Lower_To_Upper(string text)
{
if (Char.IsLower(text[0]) == true) { text = text.Replace(text[0], char.ToUpper(text[0])); return text; }
return text;
}
Hope this will help you ! here i made two methods taking as parameter any string and return the string with the first letter uppercase or lowercase according to the method you will use
string test = "ConfigService";
string result = test.Substring(0, 1).ToLower() + test.Substring(1);
I would simply do this:
Char.ToLowerInvariant(yourstring[0]) + yourstring.Substring(1)
Simple and gets the job done.
EDIT:
Looks like this thread had the same idea. :)
This can help you,changes first character to lower if it is upper and also checks for null or empty and only whitespace string:
string str = "ConfigService";
string strResult = !string.IsNullOrWhiteSpace(str) && char.IsUpper(str, 0) ? str.Replace(str[0],char.ToLower(str[0])) : str;

how to check the condition in asp.net for string array

I have to check the condition in asp.net for string array
The conditions is I can either have two values 360__image.jpg and image.jpg.
I have to return the correct value from the condition
If the string has 360_image.jpg I have to return only image.jpg and cutting 360_
If the string is image.jpg I have to return the same image.jpg
Code
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[2] != "")
{
return FileName[2];
}
else
{
return FileName[0];
}
}
The problem with above code is I am getting the error
Index was outside the bounds of the array
You should check for length before accessing element from the array, that is why you are getting the exception, since split probably resulted in array of two elements.
Not exactly sure about your requirement but I think you can simplify your method as:
public string splitString(string str)
{
if (str.Contains("_")) //or check for 360__
return str.Substring(str.LastIndexOf('_') + 1);
else
return str;
}
You can use LastIndexOf:
public string splitString(string str)
{
return str.Substring(str.LastIndexOf('_') + 1);
}
Or even use LINQ Last:
public string splitString(string str)
{
return str.Split('_').Last();
}
Array has 2 elements , means idexes 0 and 1.
But you have taken into your code as FileName[2] .
This 2nd index may be wrong thats why error is comming. It may be 1.
Try with:
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[1] != "")
{
return FileName[1];
}
else
{
return FileName[0];
}
}

Remove characters before character "."

How effectively remove all character in string that placed before character "."?
Input:
Amerika.USA
Output:
USA
You can use the IndexOf method and the Substring method like so:
string output = input.Substring(input.IndexOf('.') + 1);
The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.
You could try this:
string input = "lala.bla";
output = input.Split('.').Last();
string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);
String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
return input.Substring(index + 1);
}
This will return the new word.
Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}
public string RemoveCharactersBeforeDot(string s)
{
string splitted=s.Split('.');
return splitted[splitted.Length-1]
}
A couple of methods that, if the char does not exists, return the original string.
This one cuts the string after the first occurrence of the pivot:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
This one instead cuts the string after the last occurrence of the pivot:
public static string truncateStringAfterLastChar(string input, char pivot){
return input.Split(pivot).Last();
}

Categories

Resources