Efficient Way to Add Spaces Between Characters in a String

Adding spaces after each character in a string in python (the pythonic way)

You can try the following code

' '.join(s)
Out[1]: 'H e l l o S t a c k O v e r f l o w'

Adding spaces between characters in string C++

You can write this conveniently with the range-v3 library. So given:

namespace rs = ranges;
namespace rv = ranges::views;

std::string input = "123";

If you just want to print the string with interspersed spaces, you can do:

rs::copy(input | rv::intersperse(' '), 
rs::ostream_iterator<char>(std::cout));

And if you want to store the result in a new string, you can do:

auto result = input | rv::intersperse(' ') | rs::to<std::string>;

Here's a demo.

I think this is about as efficient as it can reasonably get, but more importantly, it's very readable.

Adding spaces between character in a String C#

You can use Linq, first Aggregate the string by adding spaces then use Replace to remove the space on the right of each hyphen.

string initial = "~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))";
string result = initial.Aggregate("", (c, i) => c + i + ' ').Replace(" - ", " -").Trim();

Trying to add spaces between characters in a string in c#

Something like this

strResult= yourString(" ", name.Reverse());

Add a space between characters in a String

"hello".split('').join(' '); // "h e l l o"

Python add a space between special characters and words

You could simply scan the complete line and selectively add space for each character that is neither alphabet nor a space.

s = 'This is a⓵⓶⓷string'
t = ''
for x in s :
if not str.isalpha(x) and x != ' ' :
if t[-1] != ' ':
t+= ' '
t += x
t += ' '
else: t += x

this works for example you have given.



Related Topics



Leave a reply



Submit