Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a character at specific index of string using c#?

Tags:

c#

winforms

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?

like image 573
user1327064 Avatar asked Oct 03 '12 17:10

user1327064


People also ask

How do you add a specific index to a string?

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.

How do you insert a character in the middle of a string in C?

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.

How do you add characters to a 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.

How do I add a substring to a string?

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.


1 Answers

Instead of if (enteredtext.IndexOf('#', 3, 3) == -1) you can just do:

if(enteredtext[3] != '#')
  enteredtext = enteredtext.Insert(3, "#");
like image 118
Magnus Avatar answered Oct 02 '22 23:10

Magnus