-2

Write a Java program to capitalize the first letter of each word in a sentence.

For this, I have written a java program but it is throwing an error

"result of string.replace(),is ignored";

my code

package com.company;

import java.util.Scanner;

public class uppercase_1srchar_of_string {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("enter the string :");
        String a = sc.nextLine();

        for(int i = 0; i < a.length(); i++) {
            if(a.charAt(i) == ' ') {
                char c;
                char d;
                c = a.charAt((i + 1));
                d = Character.toUpperCase(c);
                a.replace(a.charAt((i + 1)),d);
            }
        }

        System.out.println(a);
    }
}

I don't know where I did make a mistake.

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • 5
    Please read [mcve] and enhance your question accordingly. Dont ask us to think through what exactly your code is doing, to then think up examples where it might go wrong. Show us the example data you used, with actual vs expected output please. – GhostCat Oct 08 '21 at 07:15
  • 2
    And unrelated: Learn about java naming conventions. Class name go UpperCamelCase, always. And you never use "_" in names (unless SOME_CONSTANT). And: use meaningful names for your variables. c, d, a ... all of that means nothing to a human reader! – GhostCat Oct 08 '21 at 07:15
  • 3
    "_result of string.replace(),is ignored_", yes, this is a helpful warning for you. `String#replace()` returns a `String`, which you ignore. It does not alter the `String` it was called on, because strings are immutable. – maloomeister Oct 08 '21 at 07:16
  • 1
    Unrelated 2: dont forget to test your code with a string that ENDS with a space. You got another bug sitting in your code, waiting for that scenario ... – GhostCat Oct 08 '21 at 07:16
  • 1
    There are some issues with the code as others pointed out but try assigning the results of `replace`so that it is not ignored: `a = a.replace(...)` – Cristian Ramon-Cortes Oct 08 '21 at 07:17
  • 1
    Does this answer your question? [String.replace result is ignored?](https://stackoverflow.com/questions/36024703/string-replace-result-is-ignored) – Filburt Oct 08 '21 at 07:23

3 Answers3

1

Java's String.replace method does not make a mutation of the string, it returns a new string with the performed replacement.

See here.

You will need to rethink your design. One approach is to copy the string, then scan through the original while progressively replacing the copy.

Something like this:

package com.company;

import java.util.Scanner;

public class uppercase_1srchar_of_string {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the string :");
        String a = sc.nextLine();

        String b = a;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == ' ') {
                char c = a.charAt((i + 1));
                char d = Character.toUpperCase(c);
                
                b = b.replace(a.charAt(i + 1), d);
            }
        }

        System.out.println(a);
    }
}

You might even be able to just replace a, like this:

package com.company;

import java.util.Scanner;

public class uppercase_1srchar_of_string {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the string :");
        String a = sc.nextLine();

        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == ' ') {
                char c = a.charAt((i + 1));
                char d = Character.toUpperCase(c);

                a = a.replace(a.charAt(i + 1), d);
            }
        }

        System.out.println(a);
    }
}
0009laH
  • 1,960
  • 13
  • 27
Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
  • thanks bro! its working but it doing all character in the string to upper case,my mean if input is: dogi,tomy,meggi then output is : dogi,ToMy,Meggi. how to rectifi it ? – Vishu's study point Oct 08 '21 at 16:18
0

Use replaceAll

String a = "Write a Java program to capitalize the first letter of each word in a sentence.";

String b = Pattern
        .compile("([^a-zA-Z]*)([a-zA-Z]+)")
        .matcher(a)
        .replaceAll(w ->
                w.group(1) + w.group(2).substring(0, 1).toUpperCase() + w.group(2).substring(1));

System.out.println(b);

with output

Write A Java Program To Capitalize The First Letter Of Each Word In A Sentence.

(Note: the word definition is not clear at all, change it according to your needs see e.g. https://www.jrebel.com/blog/java-regular-expressions-cheat-sheet )

josejuan
  • 9,338
  • 24
  • 31
0

Here is Java's streamy code to do the same without using replace method at all,

import java.util.Arrays;
import java.util.stream.Collectors;

public class HelloWorld{

     public static void main(String []args){
        String data = "Hello world is my 1st program, wow i am amazed";
        String output = Arrays.stream(data.split(" "))
                              .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
                              .collect(Collectors.joining(" "));
                              
        System.out.println("Output: " + output);
     }
}

which outputs following,

Output: Hello World Is My 1st Program, Wow I Am Amazed

You can play around above solution online at https://www.tutorialspoint.com/compile_java8_online.php

Dharman
  • 30,962
  • 25
  • 85
  • 135
Krushnat Khavale
  • 416
  • 2
  • 4
  • 14