-1

I want to find out the length of last word in a given string(a). A word is defined as a sequence of characters without a space(' '). The condition is not to use any of the library functions in doing this. I know its possible in C++. Can it be done in Java too? I did it using the following:

for(char c:a.toCharArray()) //this is not correct though. I need one without using an inbuilt method(considering its possible)

Is there a method that does not use the library functions?

edit:

Here is the solution in C++. Note it doesn't use a library function not even strlen() at any point.

class Solution {
public:
    int lengthOfLastWord(const string &s) {
        int len = 0;
        while (*s) {
            if (*s != ' ') {
                len++;
                s++;
                continue;
            }
            s++;
            if (*s && *s != ' ') len = 0;
        }
        return len;

    }};
Abhishek Agarwal
  • 1,190
  • 2
  • 19
  • 38

3 Answers3

1

Your C++ code is invalid: you can't do pointer arithmetic on a reference. You could change the method signature type to:

int lengthOfLastWord(const char* s) {

and then it compiles and looks like it works (provided the array is null-terminated).

As such, roughly analogous code in Java would use a zero-terminated byte[]:

int longestWord(byte[] cs) {
  int len = 0;
  for (int i = 0; cs[i] != 0; i++) {
    // ...
  }
  return len;
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Solution 1:

for (int i = 0, n = a.length(); i < n; i++) {
    char c = a.charAt(i);
}

Solution 2:

char[] chars = a.toCharArray();
for (int i = 0, n = chars.length; i < n; i++) {
    char c = chars[i];
}
Akceptor
  • 1,914
  • 3
  • 26
  • 31
0

Here is a way to do:

String msg = "Hello everybody I'm Here";
String lastWord = msg.split(" ")[msg.split(" ").length-1];

System.out.println(lastWord);// "Here"
poxen8
  • 33
  • 1
  • 7