Write a Program to Print Next to Last Word of a Sentence

Java

import java.util.*;

class LastString {

public static void main(String args[])

{

String string = “”;

Scanner in = new Scanner(System.in);

System.out.println(“Enter a sentence : “);

string= in.nextLine();

System.out.println(“Last word of the sentence is : ” + string.substring (string.lastIndexOf (‘ ‘), string.length()));

}

}

C

#include <stdio.h>

int main()
{ char str[20];
printf(“enter string”);
gets(str);
getLastWord(str);
char lastword[5];
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 0;
}

C++

#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;
}

2 comments on “Write a Program to Print Next to Last Word of a Sentence”