Rushabh Oswal
Rushabh Oswal

Reputation: 25

String substring error

Question:

Input:-gandhi                      output:- Gandhi
Input:-mahatma gandhi              output:- M. Gandhi 
Input:-Mohndas Karamchand ganDhi   output:- M. K. Gandhi

Answer:

public class Chef_NITIKA {

    static Scanner scan=new Scanner(System.in);

    public static void main(String[] args) {
        String name=    myString();
        System.out.println("nam is :"+name);
        mySformatter(name);

    }

    private static void mySformatter(String name) {
           int count=0;
          for(char c:name.toCharArray()){
              if(c==' '){
                  count+=1;
              }
          }
          System.out.println(count+" blank spaces");
          if(count==0){
              char ch=name.charAt(0);
              name=Character.toUpperCase(ch)+name.substring(1);
              System.out.println("nam is :"+name);
          }
          else if(count==1){
              char ch=name.charAt(0);
             name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(".")+1);
             char c=subname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name=Character.toUpperCase(ch)+"."+subname;
              System.out.println("nam is :"+name);
          }
          else if(count==2){
              char ch=name.charAt(0);
            // name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(" ")+1);
             System.out.println(subname);
             String subsubname=subname.substring(name.indexOf(" "));
             System.out.println(subsubname);
             char c=subname.charAt(0);
             char c1=subsubname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
              System.out.println("nam is :"+name);
          }
    }

    private static String myString() {
       System.out.println("enter the string");
       String s=scan.nextLine();
       StringBuffer name=new StringBuffer();
     //  name.append(s);
       return s;
    }
}

I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh

Is there any efficient way to solve this problem?

undesired output:-

enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack

I want the output as I.W.OnStack

Upvotes: 0

Views: 1129

Answers (3)

msanaullah
msanaullah

Reputation: 37

@Rushabh Oswal you can get desired result by below method

    private static void mySformatter(String name) {
            String [] tempArray=name.split(" ");
            StringBuilder outputStr=new StringBuilder();
            int len=tempArray.length;
            for(int i=0;i<len;i++){
                String str=tempArray[i];
                if (str.isEmpty())
                   continue;

                if(i==len-1)
                outputStr.append(Character.toUpperCase(str.charAt(0))).append(str.substring(1).toLowerCase());
            else
                outputStr.append(Character.toUpperCase(str.charAt(0))).append(". ");

            System.out.println(outputStr.toString());   
        }

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

Just split the name into components and then form the abbreviations you want:

public static String getName(String input) {
    String[] names = input.split("\\s+");
    String output = "";

    // replace 1st through second to last names with capitalized 1st letter
    for (int i=names.length; i > 1; --i) {
        output += names[names.length - i].substring(0, 1).toUpperCase() + ". ";
    }

    // append full last name, first letter capitalized, rest lower case
    output += names[names.length - 1].substring(0, 1).toUpperCase()
           + names[names.length - 1].substring(1).toLowerCase();

    return output;
}

public static void main(String[] args) {
    System.out.println(getName("gandhi"));
    System.out.println(getName("mahatma gandhi"));
    System.out.println(getName("Mohndas Karamchand ganDhi"));
}

Output:

Gandhi
M. Gandhi
M. K. Gandhi

Demo here:

Rextester

Update:

Here is a link to a demo where I have corrected your original code, at least partially. The issue was the following line:

String subsubname = subname.substring(name.indexOf(" "));

which I changed to this:

String subsubname = subname.substring(subname.indexOf(" ") + 1);

You were not correctly identifying the first character of the third portion of the name. This being said, your current approach is verbose, hard to read, and inflexible. In practice, you would probably want to use a leaner approach to this problem.

Upvotes: 2

Almas Abdrazak
Almas Abdrazak

Reputation: 3632

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stack;

import java.util.Scanner;
import java.util.StringTokenizer;

/**
 *
 * @author xxz
 */
public class NAmes {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final String name = sc.nextLine();
        System.out.println(formatedString(name));
        sc.close();
    }

    private static String formatedString(String name) {
        if(name!=null && name.length()!=0){
            final StringTokenizer tokenizer = new StringTokenizer(name, " ");
            StringBuilder result = new StringBuilder("");
              while(tokenizer.hasMoreTokens()){
                StringBuilder currentToken =new StringBuilder(tokenizer.nextToken());

                if(!tokenizer.hasMoreTokens()){
                    result.append(currentToken.toString().toUpperCase());
                } else{
                    result.append(currentToken.toString().toUpperCase().charAt(0)+". ");
                }
            }
            return result.toString();
        }
        return "";
    }
}

Upvotes: 2

Related Questions