Delete string until it reaches the character and ":"

Asked

Viewed 224 times

2

How to delete a part of the string until it reaches the ":" character. I was able to delete ":" using the code below:

Example String: uma_phrase_random: Ronison

string url = empresaweb2;
string resultado = url.Substring(0, url.IndexOf(':'));
txbEmpresa.Text = resultado;

Result: a random phrase

Since the result I desire is only the name: Ronison

Remembering that I don’t know the length of the sentence before the name.

  • 1

    Try this... url.Substring(url.IndexOf(':'), url.Length - 1); You start substring from the point where it is : and go to the end of the string

2 answers

6

In your code there is no reason why you remove anything, nor is it possible in standard C# code. You take another part of the code.

You can take it from the current position until the end. But do not forget to check if you found the character you are looking for, otherwise it will give error and your application will break.

using static System.Console;

public class Program {
    static void Main() {
        var url = "http://abc.com";
        var posicao = url.IndexOf(':');
        if (posicao < 0) return; //aqui você trata como quiser se não achar a string
        WriteLine(url.Substring(posicao));
        WriteLine(url[posicao..]); //só para C# 8
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

In the second line being printed I am using C# 8 which has the advantage of being faster and not making allocation.

In your code:

var posicao = empresaweb2.IndexOf(':');
if (posicao < 0) return; //aqui você trata como quiser se não achar a string
txbEmpresa.Text = empresaweb2.Substring(posicao);

5


Simple example

See this example for a better understanding of code

string url = "uma_frase_aleatória: Ronison";
string resultado = url.Split(':')[url.Split(':').Length - 1];
Console.Write(resultado);

Execute

The method Split divides the string in a array, the division is made using the char ':', then on each occurrence of ':' a new one is created string namely the string "uma_frase_random: Ronison" becomes the array

[ "uma_frase_aleatória", " Ronison" ]

And then we got the latest index on array that is

" Ronison"

With your code

Now applying the same idea but in your code

string url = empresaweb2;
string resultado = url.Split(':')[url.Split(':').Length - 1];
txbEmpresa.Text = resultado;
  • 1

    Thank you all! I managed to do it by following the @Wictor Chaves method. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.