以下是開發Android 過程中的一些有關"字串"及"數學運算"的技巧, 記錄在此主要是方便本人日後翻閱, 也與大家分享
(1) Textview 的文字處理
如 text1 是 Textview, 並不是String, 而是 CharSequence, 以面是一些可執行的程式
text1.setText("ABC")
text1.setText(String.valueOf(time)); //int time
text1.getText()
text1.getText().toString() // CharSequence 變為String
text1.getText().toString().substring(0,1) //取左邊起第1及2 個字元
text1.length()
要把文字right justify (靠右),加入以下到main.xml
<TextView>
...
android:gravity="center_vertical|right"
...
</TextView>
(2) primitive data types:
- byte : A byte variable is an 8-bit signed integer between -128 and 127. Often used for arrays.
- short : A short variable is a 16-bit signed integer between -32,768 and 32,767. Again, often used for arrays.
- int : An int variable is a 32-bit signed integer between -2,147,483,648 and 2,147,483,647. This is the most commonly used “number” variable.
- long : A long variable is a 64-bit signed integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Used when the int data type isn’t big enough.
- float : A float variable is a single precision 32-bit floating point number.
- double : A double variable is a double-precision 64-bit floating point number. Use this data type for decimal values.
- boolean : A boolean variable has only two possible values: true and false. Use this data type for conditional statements.
- char : A char variable is a single 16-bit Unicode character.
(3) 數字變字串
最簡單的方法
int j=100;
String x = "" + j;
或者
String testString = Integer.toString(j);
(4) 字串變數字
Convert a String to an int call the static method parseInt() on the Integer class. Below is an example:
String string = "123"; int value = Integer.parseInt(string)
Convert a String to a long
call the static method parseLong() on the Long class. Below is an example:
String string = "123";
long value = Long.parseLong(string);
Convert a String to a float
call the static method parseFloat() on the Float class. Below is an example:
String string = "123.4";
float value = Float.parseFloat(string);
Convert a String to a double call the static method parseDouble() on the Double class. Below is an example:
String string = "123.4";
double value = Double.parseDouble(string);
Convert a byte array to String
byte[] byteArray = new byte[] {87,79,87,46,46,46}; String value = new String(byteArray);
or
String value = new String(byteArray,"UTF-8");
(5) 數字轉換
Float 轉 Double , 指定小數位Double USRMB;
Float USRMBfloat = 3.145656456; String tempfloat2 = String.format("%.2f",USRMBfloat);
USRMB = Double.parseDouble(tempfloat2);
Double 轉 Float
Double USRMB = 3.145656456;
Float USRMBfloat;
USRMBfloat = USRMB.floatValue());
(6) 只讓Apps 直向顯示
可以在 AndroidManifest.xml 上加入android:screenOrientation="portrait" 即可, 例如
<activity
android:name=".NumberActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
(7) 字串處理
找出文字的長度
String test="I am happy";
int i;
i = test.length();
加入 CR/LF
String test;
test = "I am happy \nYou are happy too";
concat()
把兩個字串加在一起. 你亦可用 '+' 號把兩字串加在一起
contains()
檢查字串中是否包特定字串
if (line.contains("you")==true)
{
.......
}
把句子中顯示指定字串的次數找出來
輸入句子及字串內容, 執行findsubstringoccurrence 便會把多字次數的結果回傳
public int findsubstringoccurrence(String fullstring, String findStr){
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = fullstring.indexOf(findStr,lastIndex);
if (lastIndex != -1) {
count ++;
lastIndex+=findStr.length(); }
}
return count;
}
replace(), replaceFirst(), replaceAll()
更換String 中的部份內容,replace() 已可以把句子中所有要變換的字串都一次處理
例句
String1 = String1.replace("cry", "happy");
注意 :單執行String1.replace("cry", "happy"); 是不成功的, 一定把結果放入一個新variable 內
split()
把一個長字串拆散為數個較短字串
例句
someWords = "Red Orange Yellow Green Blue Indigo";
String[] aColors = someWords.split(" ");
// aColors[0] contain "Red"
// aColors[1] contain Orange"
// aColors[2] contain Yellow"
以上 splits 方法在低版本 Android SKD 不支持, 可改用 StringTokenizer
StringTokenizer
StringTokenizer tokens = new StringTokenizer(someWords , " ");
String first = tokens.nextToken();
String second = tokens.nextToken();//小心如有tokens 為 NULL (零長度) StrngTokenizer 會令程式死亡自己關閉
substring()
抽出一個字串中的部份字串String test;String substr=mysourcestring.subString(startIndex,endIndex);eg.
test = "How are you?";
test = test.substring(1, 3); 從左起取1,2位字母 , 即 "ow"
toUpperCase(), toLowerCase()
改變字體的大小草
例句
String strUpperCaseVersion = strVowels.toUpperCase();
String strLowerCaseVersion = strVowels.toLowerCase();
trim()
移走字串前後空白
例句
String notrimword = strsource.trim();
endsWith()
字串尾的字元 (尤其合中文字)
例句
Sting i="快樂";
int k=i.length(); //k=2
if ((k>1) && i.endsWith("樂")) {i = i.substring(0, k-1);} // i 變為 "快"
取 String s 的第一位的 character, 放入chartemp
char chartemp = String.valueOf(s).charAt(0)
charSquence 轉 String
CharSequence in = "some string";String cs = in.toString();
String 轉 charSquenceString
a = "test";
CharSequence c = a;
(8) 判斷
switch (item){
case 1:
break;
case 2:
break;
}
if (i==3) {xxxxxx;}
else if (i==4) {xxxxxx;}
(9) 在程式內改變 Activity 的 Title
setTitle("This is a new title");
(10) 比較字串
不要採用 "==" 去比較兩個字串是否一樣,因為 == 是用來比較 object references 而並非內容, 請採用
editText1.toString().equals("match string")或
String str1;
Str1.equals("match string")
(11) 把EditText 中的文字變為整數
在 XML 檔內加入 android:inputType="number" , 強制容許數字輸入.
文字導出數字
Int number = Integer.parseInt(myEditText.getText().toString()))
(12) 把數字變為文字放到EditText
myEditText.setText(String.valueOf(number)); |