String trim();
返回一個字串,刪除掉了頭部和尾部的空格。
| 代碼如下 |
複製代碼 |
|
boolean startsWith(String prefix);
boolean endsWith(String suffix); |
分別判斷字串是不是以prefix開頭或者以suffix結尾。
| 代碼如下 |
複製代碼 |
|
int indexOf(String str);
int indexOf(String str,int fromIndex);
int indexOf(int cp);
int indexOf(int cp,int fromIndex); |
傳回值是第一個子串的開始位置。如果需要返回最後一個子串的請使用lastIndexOf,參數表一致。
2.常用的API用代碼寫出來好了。自己試了一下,和C++的string操作很像。
| 代碼如下 |
複製代碼 |
|
import java.lang.StringBuilder;
public class temp
{
public static void main(String[] args)
{
StringBuilder builder = new StringBuilder();
builder.append("string");
builder.append('c');
builder.setCharAt(2,'v');
builder.insert(3,"ins");
builder.insert(4,'a');
builder.delete(4,6);//這句刪除的是4和5,即刪除4~6之間不包括6的部分。
String str = builder.toString();
System.out.println(str);
}
} |
3.如果需要使用Scanner讀入資料,請在標頭檔中加入
import java.util.*;
PS:nextLine()的似乎和C++中的getline()在效果方面有些區別。假如剛剛在螢幕上輸出了一個endl,那麼下一次getline的時候會直接把這個endl讀進字串(至少OJ上有時會這樣),而剛才的嘗試中nextLine()不會有這個問題。
如果需要讀入密碼(非明文)的話可以採用java.lang.System和java.io.Console中的Console類:
| 代碼如下 |
複製代碼 |
|
import java.util.*;
import java.lang.System;
import java.io.Console;
public class temp
{
public static void main(String[] args)
{
Console cons = System.console();
String username = cons.readLine("User name: ");
char[] passwd = cons.readPassword("Password: ");
System.out.println(passwd);
}
} |