Remove characters before character "."

C#

C# Problem Overview


How effectively remove all character in string that placed before character "."?

Input: Amerika.USA

Output: USA

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You could try this:

string input = "lala.bla";
output = input.Split('.').Last();

Solution 3 - C#

string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);

Solution 4 - C#

String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
    return input.Substring(index + 1);
}

This will return the new word.

Solution 5 - C#

public string RemoveCharactersBeforeDot(string s)
{
 string splitted=s.Split('.');
 return splitted[splitted.Length-1]
}

Solution 6 - C#

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

Solution 7 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlovijiView Question on Stackoverflow
Solution 1 - C#casperOneView Answer on Stackoverflow
Solution 2 - C#ChristianView Answer on Stackoverflow
Solution 3 - C#Itay KaroView Answer on Stackoverflow
Solution 4 - C#lukeView Answer on Stackoverflow
Solution 5 - C#ryudiceView Answer on Stackoverflow
Solution 6 - C#Niko ZarzaniView Answer on Stackoverflow
Solution 7 - C#BenView Answer on Stackoverflow