Program Discussion :: Strings
51 / 60
Write a program to enter a sentence then find 2 last word of sentence
Answer:
#include
using namespace std;
string getLastWord(string text)
{
string lastword="";
int last=text.size()- 1;
int beginlast=0;
if text == "";
return "";
for (int i=last; i>=1; i--)
{
if (isspace(text[i]))
beginlast=beginlast+i;
}
for (int k=0; k!=text.size; k++)
{
if (isalpha(text[k]))
lastword=lastword+lastword[k];
}
return lastword;
}
int main()
{ char str[20];
coutstr;
getLastWord(str);
return 0;
}
Asked In ::
Language:
Manoj Kumar
15 Jun, 2017 11:06 PM
<!DOCTYPE html>
<html>
<body>
<?php
function Second_last() {
// input string
$str ="india is my country";
echo "Input string is :" . $str."<br/>";
// conversion of string into array
$arr = explode( " ", $str);
// counting lengh of array
$arrlength=count ($arr);
// printing 2nd last value( including blank space)
echo $arr[$arrlength-2];
}
Second_last();
?>
</body>
</html>
Language:
Lekha
7 Jul, 2017 9:30 AM
#include <iostream>
using namespace std;
string getLastWord(string text)
{
string lastword="";
int last=text.size()- 1;
int beginlast=0;
if text == "";
return "";
for (int i=last; i>=1; i--)
{
if (isspace(text[i]))
beginlast=beginlast+i;
}
for (int k=0; k!=text.size; k++)
{
if (isalpha(text[k]))
lastword=lastword+lastword[k];
}
return lastword;
}
int main()
{ char str[20];
printf("enter string");
gets(str);
getLastWord(str);
return 0;
}
Language:
Neel
7 Jul, 2017 9:30 AM
#include <iostream>
using namespace std;
string getLastWord(string text)
{
string lastword="";
int last=text.size()- 1;
int beginlast=0;
if text == "";
return "";
for (int i=last; i>=1; i--)
{
if (isspace(text[i]))
beginlast=beginlast+i;
}
for (int k=0; k!=text.size; k++)
{
if (isalpha(text[k]))
lastword=lastword+lastword[k];
}
return lastword;
}
int main()
{ char str[20];
cout<<"enter string";
cin>>str;
getLastWord(str);
return 0;
}
Language:
Amit
25 Aug, 2017 12:14 AM
class Next2LastWord
{
public static void main(String args[])
{
String str="word of sentence";
String[] s=str.split(" ");
String sLastWord=s[s.length-2];
System.out.println(sLastWord);
}
}