I have a string entered by the user in the text box. I need to insert char '#' in the string if not entered by the user.
expected format : aaa#aa#a
Here is the code to verify and correct the expected format:-
if user entered this: aaaaaa,
if (enteredtext.Length >= 7 && enteredtext.EndsWith(","))
{
if (enteredtext.IndexOf('#', 3, 3) == -1)
enteredtext = enteredtext.Insert(3, "#");
if (enteredtext.IndexOf('#', 6, 6) == -1)
enteredtext= enteredtext.Insert(6, "#");
}
Any other best way to achieve it?
The splice() method is used to insert or replace contents of an array at a specific index. This can be used to insert the new string at the position of the array. It takes 3 parameters, the index where the string is to be inserted, the number of deletions to be performed if any, and the string to be inserted.
Note that a string in C is a char[] , i.e. an array of characters, and is of fixed size. What you can do is, create a new string that serves as the result, copy the first part of the subject string into it, append the string that goes in the middle, and append the second half of the subject string.
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
Insert the substring from 0 to the specified (index + 1) using substring(0, index+1) method. Then insert the string to be inserted into the string. Then insert the remaining part of the original string into the new string using substring(index+1) method. Return/Print the new String.
Instead of if (enteredtext.IndexOf('#', 3, 3) == -1)
you can just do:
if(enteredtext[3] != '#')
enteredtext = enteredtext.Insert(3, "#");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With