Program Discussion :: Strings
25 / 60
Write an efficient program to reverse the string, words in a given sentence.
Answer:
#include
#include
#include
using namespace std;
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
coutstr;
/* 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
Asked In ::
Language:
Madhu
15 Jun, 2017 10:12 AM
<!DOCTYPE html>
<html>
<body>
<?php
function String_word_rev() {
// input string
$str ="what is your name";
echo "Input string is :" . $str."<br/>";
// conversion of string into array
$arr = explode( " ", $str);
// counting lengh of array
$arrlength=count ($arr);
// initialising an empty array and its initial index
$arrc=array(); $j=0;
// loop for reading the input array
for( $x =$arrlength; $x>=0; $x--)
{
$arrc[$j]=$arr[$x]; // reversing the array
$j++;
}
// conversion of array into string
$name= implode (" ",$arrc);
echo $name; // printing string in reverse order
}
String_word_rev();
?>
</body>
</html>
Language:
Lokeshwari
7 Jul, 2017 9:30 AM
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and
// update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
// Driver program to test above function
int main()
{
char str[] = "89789";
int val = myAtoi(str);
printf ("%d ", val);
return 0;
}
Language:
Nikhil
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
void main()
{
int i, j = 0, k = 0, x, len;
char str[100], str1[10][20], temp;
cout<<"enter the string :";
cin>>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++)
{
cout<<str1[i];
}
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.util.*;
public class Reverse
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string: ");
String str=sc.nextLine();
String s[]=str.split(" ");
String rev="";
for(int i=s.length-1;i>=0;i--)
{
rev +=s[i]+" ";
}
System.out.println("Reversed String is: "+rev.substring(0, rev.length() - 1));
}
}