How to Insert a Character in a String at a Certain Position

How to insert a character in a string at a certain position?

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());

How to insert character in a string at a specific position?

You can use the substr() function!

If u want to insert 25 inside $str="Hello From Other Side "; at the position 2!

U can do

$pos=2;
$new_string= substr($str, 0, $pos). "25" . substr($str, $pos);

and the results would be:

"He25llo From Other Side "

How to add a string in a certain position?

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

Insert a string at a specific index

You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}

Example

String.prototype.splice = function(idx, rem, str) {    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"

Java:adding char to a specific position in a Strings(Performance)

In this case I would use a StringBuilder :)

String yourString = "Hello";

StringBuilder sb = new StringBuilder(yourString);
sb.insert(2, '_');

System.out.println(sb.toString());

The output is: He_llo

EDIT: Replaced StringBuffer with StringBuilder

Insert into a certain position in a string

This should work:

string s = "MOT1-G-PRT45-100";
int index = ... // position to insert
string res = s.Insert(index, c + separator);

Inserting string at position x of another string

var a = "I want apple";var b = " an";var position = 6;var output = [a.slice(0, position), b, a.slice(position)].join('');console.log(output);


Related Topics



Leave a reply



Submit