Program to print the alphabets before and after the blank space in a sentence

1.1k views Asked by At

Example- Input:- India is a great nation Output:- a and i, s and a, a and g, t and n

public class PrintSpace
{
    public void accept(String str)
    {
        char ch='\u0000';
        int i=0;
        int l=0;
        l=str.length();
        for(i=0;i<l;i++)
        {
            ch=str.charAt(i);
            if(ch==" ")
            {
                System.out.print((i-1)+"and"+(i+1));
            }
        }
    }
}
2

There are 2 answers

1
shruti1810 On

Try this:

    public static void accept(String str)
    {
        char ch='\u0000';
        int i=0;
        int l=0;
        l=str.length();
        for(i=0;i<l;i++)
        {
            ch=str.charAt(i);
            if(ch == ' ')
            {
                System.out.println(str.charAt(i-1)+" and "+str.charAt(i+1));
            }
        }
    }
0
Uma Kanth On

char cannot be compared to String.

replace

if(ch == " ") 
 {
 }

with

if(ch == ' ')
 {
 }

You are printing the index, not the character,

use str.charAt(i- 1) + " and "+ str.charAt(i + 1)

char ch='\u0000';
int i=0;
int l=0;
String str = "India is a great nation";
l=str.length();
for(i=0;i<l;i++)
  {
     ch=str.charAt(i);
     if(ch==' ')
       {
         System.out.println(str.charAt(i-1)+"and"+str.charAt(i+1));
       }
   }