Replace a Word in a String by Indexing Without "String Replace Function" -Python

Javascript using .replace() at a specific index of the search

You can do this with a little bit of manipulation, not requiring any regex.

I used this function to fetch the position (index) of another string within a string.

From there, it's as simple as returning a substring from the beginning to the found index, injecting your replacement, and then returning the rest of the string.

function replaceAt(s, subString, replacement, index) {  const p = s.split(subString, index+1).join(subString);  return p.length < s.length ? p + replacement + s.slice(p.length + subString.length) : s;}
console.log(replaceAt("my text is my text and my big text", "my", "your", 2))console.log(replaceAt("my text is my text and that's all", "my", "your", 2))console.log(replaceAt("my text is my my my my text", "my", "your", 2))

How to replace a word in a string in java without using .replace

I already figure out a solution, I used...

int indexStart = labelCode.getSelectionStart(); 
int indexEnd = labelCode.getSelectionEnd();
String a = codeText.substring(0,indexStart);
String b = codeText.substring(indexEnd,codeText.length());
String finalAns = a+newVar+b;

I used Spannable... .getClickableSpan to detect the tapped word on the label

How to replace only a specific word from the end of the string in PHP?

Based on the conditions you mentioned you can do something like below. Find the word count and then check is home available in the string and then find the index of the house . So then you can check does that index match to last index of the word array (count($wordArray)) - 1)

$string1 = 'this is my house';
$string2 = 'this house is mine';
$wordArray = explode(' ', $string1); // make the array with words
//check the conditions you want
if (in_array('house', $wordArray) && (array_search('house', $wordArray) == (count($wordArray)) - 1)) {
$string1 = str_replace('house', 'dog', $string1);
}
echo $string1;

How do I replace a substring in java without using the replace method and if the function has multiple parameters?

I think the easiest way is to use the String.index method. Note that this solution will take a string larger than a letter. And it is case sensitive.

String ss = replaceWordWithLetter("aabaacaaa", "aa","a");
System.out.println(ss);

Prints

abacaa
  • get the index of the word in the string.
  • append everything up to that to the current result
  • append your replacement string.
  • replace the original string with the string after the location of the word (i.e word + wlength). So the original string now begins just after the word that was found.
  • continue until the word to be replaced is no longer found (indexOf returns -1).
public static String replaceWordWithLetter(String str, String word, String c) {
String result = "";
int idx = 0;
int wlength = word.length();
while ((idx = str.indexOf(word)) >= 0) {
result += str.substring(0, idx)+c;
str = str.substring(idx+wlength);
}
return result+str;
}

Replace word in string in a specific position

I tried to implement a solution without using replacement, but rather iterating once over the markers and the original text, and in the meantime building the "new text" with markers applied. For simplicity, I used the tag mark, hard coded in the solution. You could fairly easily parametrize this aspect.

// suppose we are given the original text, and the markers as start-end pairs of selection character positionsconst text = `Lorem ipsum dolor sit amet, consectetur Lorem adipiscing elit. Vivamus ipsum Lorem eros, interdum ac cursus et, pulvinar Lorem at est. Integer nec rutrum ligula. In dignissim est a elit porttitor finibus.`;const markers = [{start: 77, end: 82}, {start: 40, end: 45}]; // positions defining the 2nd and the 3rd occurence of Lorem, chosen arbitrarily
function markSelections(text, markers) { // sort markers just in case the are not sorted from the Storage const sortedMarkers = [...markers].sort((m1, m2) => m1.start - m2.start); let markedText = ''; let characterPointer = 0; sortedMarkers.forEach(({start, end}) => { markedText += text.substring(characterPointer, start); markedText += '<mark>'; markedText += text.substring(start, end); markedText += '</mark>'; characterPointer = end; }); // add the remaining text after markers markedText += text.substring(characterPointer); return markedText;}document.write(markSelections(text, markers));
mark {  color: red;}

How to find index on a string and replace?

The second substring index should be index + 1:

String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + 1);
}

console.log("Hello World".replaceAt(5, "!!"))
console.log("Hello World".replaceAt(2, "!!"))
console.log("Hello World".replaceAt(2, "!!!"))

change words at particular location in javascript string

You need to make an array out of the string to replace by index.
The following should do the trick.

const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}

How to replace a char in a string without using Replace() in Java?

This is the code that does the same. I've commented the code to explain what it does

public class ReplaceChar {

public static void main(String... args){
String[] input =new String[]{"ababba","anaceeacdabnanbag","aabaaaavfaajaaj"};

StringBuilder result = new StringBuilder();

for (int i= 0; i < input.length;i++){
result.append(getReplacedA(input[i]));
result.append("\n");
}

System.out.println(result);

}

private static String getReplacedA(String withA){
// stringBuilder for result
StringBuilder replacedString = new StringBuilder();

// counting the number of time char 'a' occurred in String for replacement before row of 'aaa'
int charACount = 0;

// get the first index at which more than two 'aa' occurred in a row
int firstIndexOfAAA = withA.indexOf("aaa") + 1;

// if 'aaa' not occurred no need to add the rest substring
boolean addSubRequired = false;

// if the index is 0 continue till end
if (firstIndexOfAAA == 0)
firstIndexOfAAA = withA.length();
else
addSubRequired = true;

char[] charString = withA.toCharArray();

//Replace character String[] array
String[] replace = new String[]{"x","xx","xxx"};

for(int i = 0; i < firstIndexOfAAA; i++){
if (charString[i] == 'a'){
charACount++;
charACount = charACount > 3 ? 1 : charACount ;
// add the number x based on charCount
replacedString.append(replace[charACount - 1]);
}else{
replacedString.append(charString[i]);
}
}

// if the String 'aaa' has been found previously add the remaining subString
// after that index
if (addSubRequired)
replacedString.append(withA.substring(firstIndexOfAAA));

// return the result
return replacedString.toString();
}

}

Output:

xbxxbbxxx
xnxxceexxxcdxbnxxnbxxxg
xxxbxxxaaavfaajaaj

EDIT : Some Improvement You can make for some corner cases in the getReplacedA() function:

  1. Check if char 'a' is there or not in the String if not just return the String No need to do anything further.

  2. Use IgnoreCase to avoid the uppercase or lowercase possibility.



Related Topics



Leave a reply



Submit