Remove X first elements from a string

Asked

Viewed 6,140 times

2

I have the following code:

copia = num.Text;
copia = copia.Substring(cobrar.Length + 1, copia.Length);
num.Text = copia;

Where copia receives a string from a textbox and cobrar is a predefined string, I want it to "delete" the string cobrar of my string copia.

Example:

cobrar = "teste";
copia = "numero";
num.Text = cobrar + copia; //não é só isso, por isso quero remover com o Substring
resultado seria = "numero";

When I run the program it closes at that time, the IDE tells me to look at my startIndex that it would charge. Length .. What error am I commenting on?

  • Dude, improve your example a little bit and I’ll help you. It’s still kind of confusing.

  • It already worked, bro, this is a little harder to explain than the other one, but it would be to remove part of a string. My main string is the union of two or three string, hence I wanted to remove a string from this main string.

1 answer

4


You can use the method string.Remove(int start, int count) that returns a string removing content. Contents of the MSDN documentation:

Returns a new string in which a specified number of characters in the current instance, starting at the specified position were outcast.

For example,

string nome = "Leonardo VIlarinho";

// começa do primeirao caracter, e remove os 5 primeiros.
nome = nome.Remove(0, 5); // retorna "rdo VIlarinho"

Or you can still use the method string.Substring(int start) or string.Substring(int start, int count), which has a similar function to Remove(). For example,

string nome = "Leonardo VIlarinho";

// retorma uma substring começando em 5 até o fim
nome = nome.Substring(5); // retorna "rdo VIlarinho"

or

string nome = "Leonardo VIlarinho";

// retorma uma substring começando em 5 até o 3 caracteres
nome = nome.Substring(5, 3); // retorna "rdo"

There is still the immutability of string in . Net, it is worth looking at this post: What "immutable" really means?

  • I tested worked, but had done otherwise functional also using a lot of condition and two bool, then was lazy to erase and left as it was, but next I know how to do! kk

  • 1

    Yes, there are several approaches, but I recommend that you use the methods that already exist in the types. There is also the substring that can help you cut your string.

Browser other questions tagged

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