0

Ok So i have something like this:

String str = "Have.Fun.Something";
String str2 = "asd.sad.saw.sa.Something";

and i wanna remove all things from last char until first "." so output will be always

Something

1
  • i tryied str.Replace("Have.Fun.", "") Commented Apr 16, 2012 at 13:03

6 Answers 6

5

How about this:

str.Split('.').Last();
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this

str = str.Substring(str.LastIndexOf('.')+1);

Comments

1

There are a whole bunch of useful methods on an instance of a string. The best place for you to look is on MSDN.

In your particular case you can use substring and lastindexof. If the case were more complicated I'd probably suggest RegEx although this is much more involved.

String str2 = str.SubString(str.LastIndexOf('.') + 1);

2 Comments

Or exception, if no '.' would be found.
@Lorond: Indeed although I'm not sure the answer needs exception handling in this case. It would make the answer more complicated and I'm not sure the poster needs the extra complexity, but +1 for pointing it out
0

You Can use Split function Below like this :

String str = "Have.Fun.Something";
String str2 = "asd.sad.saw.sa.Something";

string[] Words= str.Split('.');

MessageBox.Show(Words[Words.Length-1].tostring());

Get Below like this

Something

Same as String str2 = "asd.sad.saw.sa.Something"; Thanks..!

Comments

0

You may use Regular Expressions (regex):

(?:.*)\.(?<myGroup>.*)

Applying the above regex, you'll have a group named 'myGroup' which has the value after the last dot

Personally, i like this options because it gives you further scalability if the need arises

If you need further assistance with regex, please say so

Comments

0

Bug free approach

public static string Substring(string input)
{
    if (!String.IsNullOrEmpty(input))
    {
        int lastIndex = input.LastIndexOf('.');
        if (lastIndex != -1)
            return input.Substring(lastIndex + 1);
    }

    return input;
}

1 Comment

Is it really bug free? What would it do for "Hello."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.