![](/img/trans.png)
[英]making a substring from string in java without using any string function
[英]Iterate on the characters in a string in Java without using any library function
我想找出給定字符串(a)中最后一個單詞的長度。 單詞被定義為不帶空格(' ')的字符序列。 條件是不使用任何庫函數來執行此操作。 我知道它在 C++ 中是可能的。 它也可以用Java完成嗎? 我使用以下方法做到了:
for(char c:a.toCharArray()) //this is not correct though. I need one without using an inbuilt method(considering its possible)
有沒有不使用庫函數的方法?
編輯:
這是 C++ 中的解決方案。 請注意,它在任何時候都不使用庫函數,甚至不使用strlen()
。
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;
}};
您的 C++ 代碼無效:您不能對引用進行指針運算。 您可以將方法簽名類型更改為:
int lengthOfLastWord(const char* s) {
然后它編譯並看起來像它工作(假設數組以空值結尾)。
因此,Java 中大致類似的代碼將使用以零結尾的byte[]
:
int longestWord(byte[] cs) {
int len = 0;
for (int i = 0; cs[i] != 0; i++) {
// ...
}
return len;
}
解決方案1:
for (int i = 0, n = a.length(); i < n; i++) {
char c = a.charAt(i);
}
解決方案2:
char[] chars = a.toCharArray();
for (int i = 0, n = chars.length; i < n; i++) {
char c = chars[i];
}
這是一種方法:
String msg = "Hello everybody I'm Here";
String lastWord = msg.split(" ")[msg.split(" ").length-1];
System.out.println(lastWord);// "Here"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.