What Is the Best Method to Swap Words in a String

What is the best method to swap words in a string

If you want to use replace, use a temporary value:

let str = '{"val":4,"right":{"val":7,"right":{"val":9,"right":null,"left":null},"left":{"val":6,"right":null,"left":null}},"left":{"val":2,"right":{"val":3,"right":null,"left":null},"left":{"val":1,"right":null,"left":null}}}';
function swap() { str = str.replace(/right/g, "temp"); str = str.replace(/left/g, "right"); str = str.replace(/temp/g, "left"); console.log(str);}
swap();

How to swap the order of specific words in a string?

Try this:

public static void main(String[] args) {

String test = "This is a test string of many words and more";
List<String> words = Arrays.asList("is", "test", "words", "more");
int size = words.size();
for (int i = 0; i < size / 2; i++) {
String firstWord = " "+words.get(i)+" ";
String secondWord = " "+words.get(size - 1 - i)+" ";
String temp = "####";
test = test.replace(firstWord, temp);
test = test.replace(secondWord, firstWord);
test = test.replace(temp, secondWord);
}
System.out.println(test);
}

How to 'swap' words (multiple characters) in a string?

Given that we want to swap words x and y, and that we don't care about the situation where they overlap, we can:

  • split the string on occurrences of x
  • within each piece, replace y with x
  • join the pieces with y

Essentially, we use split points within the string as a temporary marker to avoid the problem with sequential replacements.

Thus:

def swap_words(s, x, y):
return y.join(part.replace(y, x) for part in s.split(x))

Test it:

>>> swap_words('apples and avocados and avocados and apples', 'apples', 'avocados')
'avocados and apples and apples and avocados'
>>>

Swap words in string C++

Posted only because the OP asked for an alternative algorithm of how this can be done. There are other ways, but this has the benefit of being done entirely in place, using no additional storage besides some pointers and some lengths.

This task can be done in-place, by using a utility function to reverse a character sequence, given a pointer and length (or two pointers). You must have numerous other reliable operations at your disposal as well, including the ability to find complete words. (e.g. words that are preceded by whitespace or begin-of-string, and succeeded by whitespace or end-of-string. Write those, and test them thoroughly. Once you've done that, consider the following.

String

this is a very simple sample of words

Test Words

very of

We start by separating our two words, which you're already doing. Next we find both words, remembering their locations, using your well-tested utility functions. We know their lengths, so we can therefore calculate where they begin, and where they end.

this is a very simple sample of words
1111 22

Side note: When doing this, you'll discover the order may be backward. For example, if your word list was of very, then the result would have your word positions looking like this:

this is a very simple sample of words
2222 11

It doesn't matter, all that matters is that once you find both words, the word closest to the beginning of the string is the "first" word, and the one coming later is the "second" word from here on out.

That said (and now back to our original labeling), reverse the entire segment from the beginning of the first word through the end of the second word, not including any whitespace preceding the first, or succeeding the second:

this is a fo elpmas elpmis yrev words
22 1111

Next, reverse the two words in-place at their new homes.

this is a of elpmas elpmis very words
22 1111

And finally, reverse all characters past the end of the new first word until (but not including) the beginning of the new second word, including whitespace That means this region:

this is a of elpmas elpmis very words
xxxxxxxxxxxxxxx

and it becomes this:

this is a of simple sample very words

That's the entire algorithm. Once you find your word locations and extents you're literally four well-place segment reversals from accomplishing your goal. Obviously, care must be undertaken to ensure you do not precede before beginning of string, nor exceed past the end-of-string, should your words being swapped reside in those locations.


Update : OP-provided sample.

The OP provided a sample, apparently not understanding how the above algorithm applies, so I'm running it through that sample as well

Words

like eat

Sentance

I like to eat apples

Step 1: Locate the two words, noting their position and lengths.

I like to eat apples
1111 222

Step 2: Reverse the full segment from the beginning of the first word through the end of the second. Therefore, the segment marked with 'x' below:

I like to eat apples
xxxxxxxxxxx

becomes this:

I tae ot ekil apples
222 1111

Step 3: Reverse each word now that they're in their new locations

I eat ot like apples
222 1111

Step 4: Reverse the full segment between the two words, including whitespace. E.g. the segment marked below:

I eat ot like apples
xxxx

becomes this:

I eat to like apples

And you're done.

Swap the words of a string in Javascript

I hope this helps

var str = 'Secret Life is Beautiful Key';
var reversed = str.split(' ').reverse().join(' ');
console.log(reversed);

How to swap two words in a string?

Use replace

long_string = 'I eat food and she eat food so he can eat food'

long_string = long_string.replace('eat food', 'food eat')

print(long_string)

Output:

I food eat and she food eat so he can food eat

Edit:1

As others pointed out if your strings would have something like "great foods" then you need to consider filtering with one space before and one after to avoid replacing "great foods".

Also, if you consider the case where you get "eat food" at the beginning or at the end of your string, then appending one space to the beginning and to the end of the string solves the case.

long_string = " " + long_string + " "

long_string = long_string.replace(' eat food ', ' food eat ')

note that if you don't need the first and the last spaces added in the string, then consider removing them with:

long_string = long_string[1:-1]

Edit:2

As @Tomerikoo & @Kelly Bundy commented if you expect punctuation in the string. Then the solution would be:

import re
long_string = re.sub(r'\beat food\b', 'food eat', long_string)
Ref:

regex

re.sub

Changing position of words in a string

Looks like its a date. You can parse the string to DateTime, using DateTime.ParseExact and then use .ToString to return formatted result.

DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);
Console.Write(dt.ToString("yyyy MM dd"));

You may use that DateTime object later in your code, and also apply different formatting (if you need)

Is there a better way replace several words in a string with another word? SAS

You could use a format to convert each word in the original variable.

data have;
infile datalines dsd truncover;
input ID Description :$50. Col3 $ Col4 Col5 Col6;
datalines;
1,bla bla my mybla,C1,0,100,0
2,got me tear,C1,0,0,0
3,free text i ,C1,10,100,0
4,house roof tree!?,C1,10,100,0
5,house mugg muggle,C1,10,0,0
6,sky** computer mug mug mugs!,C3,0,20,1
;

proc format ;
value $fix (max=200)
"mug", "mugg", "mugs" = "cup"
"i", "me", "my" = " "
;
run;

data want;
set have;
fixed=description;
fixed=' ';
do index=1 to countw(description,' ');
fixed=catx(' ',fixed,put(scan(description,index,' '),$fix200.));
end;
run;


Related Topics



Leave a reply



Submit