简体   繁体   中英

Trim a string in c# after special character

I want to trim a string after a special character..

Lets say the string is str="arjunmenon.uking" . I want to get the characters after the . and ignore the rest. Ie the resultant string must be restr="uking" .

How about:

string foo = str.EverythingAfter('.');

using:

public static string EverythingAfter(this string value, char c)
{
    if(string.IsNullOrEmpty(value)) return value;
    int idx = value.IndexOf(c);
    return idx < 0 ? "" : value.Substring(idx + 1);
}

you can use like

string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length  );

Try Regular Expression Language

using System.IO;
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "arjunmenon.uking";
        string pattern = @"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";

        foreach (Match match in Regex.Matches(input, pattern))
       {
         Console.WriteLine(match.Value);
         if (match.Groups.Count > 1)
            for (int ctr = 1; ctr < match.Groups.Count; ctr++) 
               Console.WriteLine("   Group {0}: {1}", ctr, match.Groups[ctr].Value);
      }

    }
}

Result:
arjunmenon.uking
    Group 1: uking

Use Split function Try this

string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';

var restr = str.Substring(str.IndexOf(special) + 1).Trim();

Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:

string str = "arjunmenon.uking";
string restr = str.Split('.').Last();

You may find all the info you need here :http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx

cheers

Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?

After you make a Split, just get the last item in the array.

string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);

string restr = parts[parts.length - 1];

The variable restr will be = "evil"

string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];

I think the simplest way will be this:

string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM