xxxxxxxxxx
One Line
public class Solution
{
public string ReverseWords(string s)
=> string.Join(" ",s.Trim().Split(' ').Where(x=>x.Length>0).Reverse());
}
Another Approaches
public class Solution
{
public string ReverseWords(string s)
{
var stack = new Stack<string>();
int i=0 ,j=0;
while(j <= s.Length)
{
if( j == s.Length || s[j] == ' ' )
{
var sub = s.Substring(i,j-i);
if(j-i >= 0 && sub.Length > 0) stack.Push(sub);
i=++j;
}
else j++;
}
return string.Join(" ",stack);
}
}
xxxxxxxxxx
function wordsReverser(string){
return string.split("").reverse().join("").split(" ").reverse().join(" ")
}
console.log(wordsReverser('New string, same results.'));
xxxxxxxxxx
function reverse (word) {
word = word.split('.').reverse().join('.')
return word
}
word = 'i.like.this.program.very.much'
word = 'pqr.mno'
console.log(reverse(word))
xxxxxxxxxx
/*
* C Program to Reverse every Word of given String
*/
#include <stdio.h>
#include <string.h>
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
printf("enter the string :");
scanf("%[^\n]s", str);
/* reads into 2d character array */
for (i = 0;str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
str1[k][j]='\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
j++;
}
}
str1[k][j] = '\0';
/* reverses each word of a given string */
for (i = 0;i <= k;i++)
{
len = strlen(str1[i]);
for (j = 0, x = len - 1;j < x;j++,x--)
{
temp = str1[i][j];
str1[i][j] = str1[i][x];
str1[i][x] = temp;
}
}
for (i = 0;i <= k;i++)
{
printf("%s ", str1[i]);
}
}