-1

Some test cases are not working. May I know where I went Wrong. the test case "i love programming is working but other test case which idk are not working.

class Solution
{
    public String transform(String s)
    {
        // code here
       char ch;
    //  String s = "i love programming";
        String res=""; 
        ch = s.charAt(0); 
        ch = Character.toUpperCase(s.charAt(0));
        res +=ch;
        
        for(int i=1;i<s.length();i++){
                if(s.charAt(i) == ' '){
                    //System.out.println(i);
                    
                    ch = Character.toUpperCase(s.charAt(i+1));
                    res+=' ';
                    res+=ch;
                    i++;
                }else {
                    
                    res+=s.charAt(i);
                
                }
        }
        
        return res;
    }
}


//Some test cases are not working. May I know where I went Wrong?
Bob
  • 15
  • 2
  • 1
    Please provide the other test cases, so it is easier to tell what is wrong. – Diego Oct 13 '21 at 06:29
  • 1
    It is from gfg it does not show the other test cases – Bob Oct 13 '21 at 06:32
  • 1
    https://practice.geeksforgeeks.org/problems/upper-case-conversion5419/1/?category[]=Strings&category[]=Strings&problemStatus=unsolved&difficulty[]=-2&page=1&query=category[]StringsproblemStatusunsolveddifficulty[]-2page1category[]Strings# – Bob Oct 13 '21 at 06:32
  • 3
    I believe what is wrong is that if a test case ends with a white space, then you will access an invalid index on the string (i + 1). You should probably treat this case or come up with a more general algorithm. For example, instead of looking if the next character is a whitespace, you can look to the previous character. If it is a whitespace, then you set it to uppercase. This way you will not access an invalid index. – Diego Oct 13 '21 at 06:38
  • 1
    ok thanks, I will try that – Bob Oct 13 '21 at 06:41
  • 2
    Actually, since your loop starts at `1`, you can simply check if `i - 1` was a whitespace. If that was the case, then you set the character to upper. This way you will never reach invalid index. – Diego Oct 13 '21 at 06:43
  • 2
    Yes you were right, it worked all the test cases passed . Thank you. – Bob Oct 13 '21 at 06:53
  • 1
    Does this answer your question? [How to capitalize the first letter of a String in Java?](https://stackoverflow.com/questions/3904579/how-to-capitalize-the-first-letter-of-a-string-in-java) – random_hooman Oct 13 '21 at 06:57

3 Answers3

0

This solution worked for me really well all the test cases passed. Thank you.

class Solution
{
    public String transform(String s)
    {
        // code here
       char ch;
    //  String s = "i love programming";
        String res=""; 
        ch = s.charAt(0); 
        ch = Character.toUpperCase(s.charAt(0));
        res +=ch;
        
        for(int i=1;i<s.length();i++){
                if(s.charAt(i-1) == ' '){
                    //System.out.println(i);
                    
                    ch = Character.toUpperCase(s.charAt(i));
                    
                    res+=ch;
              
                }else {
                    
                    res+=s.charAt(i);
                
                }
        }
        
        return res;
    }
}
Bob
  • 15
  • 2
0

There is an attempt to make uppercase a next character after the space (which should be done only if this character is a letter and if this charactrer is available). Similarly the first character of the sentence is upper cased without checking if this first letter is a letter.

It may be better to use a boolean flag which should be reset upon applying an upper case to a letter. Also, StringBuilder should be used instead of concatenating a String in the loop.

So the improved code may look as follows with more rules added:

  • make the first letter in the word consisting of letters and/or digits upper case
  • words are separated with any non-letter/non-digit character except ' used in contractions like I'm, there's etc.
  • check for null/ empty input
public static String transform(String s) {
    if (null == s || s.isEmpty()) {
        return s;
    }
    boolean useUpper = true; // boolean flag
    StringBuilder sb = new StringBuilder(s.length());
        
    for (char c : s.toCharArray()) {
        if (Character.isLetter(c) || Character.isDigit(c)) {
            if (useUpper) {
                c = Character.toUpperCase(c);
                useUpper = false;
            }
        } else if (c != '\'') { // any non-alphanumeric character, not only space
            useUpper = true; // set flag for the next letter
        }
        sb.append(c);
    }
        
    return sb.toString();
}    

Tests:

String[] tests = {
    "hello world",
    "  hi there,what's up?",
    "-a-b-c-d",
    "ID's 123abc-567def"
};

for (String t : tests) {
    System.out.println(t + " -> " + transform(t));
}

Output:

hello world -> Hello World
  hi there, what's up? ->   Hi There,What's Up?
-a-b-c-d -> -A-B-C-D
ID's 123abc-567def -> ID's 123abc-567def

Update

A regular expression and Matcher::replaceAll(Function<MatchResult, String> replacer) available since Java 9 may also help to capitalize the first letters in the words:

// pattern to detect the first letter
private static final Pattern FIRST_LETTER = Pattern.compile("\\b(?<!')(\\p{L})([\\p{L}\\p{N}]*?\\b)");
public static String transformRegex(String s) {
    if (null == s || s.isEmpty()) {
        return s;
    }
        
    return FIRST_LETTER.matcher(s)
        .replaceAll((mr) -> mr.group(1).toUpperCase() + mr.group(2));
}

Here:

  • \b - word boundary
  • (?<!') - negative lookbehind for ' as above, that is, match a letter NOT preceded with '
  • \p{L} - the first letter in the word (Unicode)
  • ([\p{L}\p{N}]*\b) - followed by a possibly empty sequence of letters/digits
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

I tried my best to understand your code as the formatting got a bit butchered in markdown I am assuming but nevertheless I gathered that this was close to what your solution was:

public class MyClass {
    public static void main(String args[]) {
      int i = 0; 
      String greet = "hello world"; 
      String res = ""; 
      res += Character.toUpperCase(greet.charAt(i++)); 
      for (; i < greet.length(); i++){
          if (greet.charAt(i) == ' '){
              res = res + greet.charAt(i) + Character.toUpperCase(greet.charAt(i + 1) );
              i++; 
          }else{
              res += greet.charAt(i); 
          }
      }
      System.out.println(res);
    }
     
}

For me this worked, but this is assuming that spaces only ever occur between words. Perhaps the answer to your question lies in these test cases and more importantly the assumptions behind these test cases. Try to gather more info about that if you can :)

Derik
  • 3
  • 2