facebook twitter hatena line email

「Java/文字列」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(置換)
 
(同じ利用者による、間の7版が非表示)
行1: 行1:
 +
==文字列数==
 +
int len = name.length();
 +
 
==文字列部分取得==
 
==文字列部分取得==
 
  String date = "2012-10-10
 
  String date = "2012-10-10
行7: 行10:
 
==置換==
 
==置換==
 
  String str = "hogeaiueo";
 
  String str = "hogeaiueo";
  System.out.println(str.replace("hoge", "piyo")); // piyoaiuoe
+
  System.out.println(str.replace("hoge", "piyo")); // piyoaiueo
 +
 
 +
System.out.println(str.replaceFirst("hoge", "piyo")); // piyoaiueo // 初回見つけた1つだけ置換
 +
 
 +
tags = tags.replaceAll("ttps://example.com/v1/event", "ttps://hoge.com/hogehoge/v1/event"); // すべて変更
 +
 
 +
==特殊文字を置換==
 +
String str = "aiu[hoge]eo";
 +
url = url.replaceFirst("\\[hoge\\]", "hogehoge"); // aiuhogehogeeo
 +
 
 +
==エンコード・デコード==
 +
import java.net.URLEncoder;
 +
try {
 +
    Log.i("test", URLEncoder.encode("[aiueo]", "UTF-8")); // %5Baiueo%5D
 +
} catch (UnsupportedEncodingException e) {
 +
    e.printStackTrace();
 +
}
 +
 
 +
import java.net.URLDecoder;
 +
try {
 +
    Log.i("test", URLDecoder.decode("%5Baiueo%5D", "UTF-8")); // [aiueo]
 +
} catch (UnsupportedEncodingException e) {
 +
    e.printStackTrace();
 +
}
 +
 
 +
==文字列検索==
 +
String str = "aiueohogeaiueo";
 +
String searchstr = "hoge";   
 +
if (str.indexOf(searchstr) != -1) {
 +
    System.out.println("hit");
 +
} else {
 +
    System.out.println("no hit");
 +
}

2019年2月26日 (火) 17:00時点における最新版

文字列数

int len = name.length();

文字列部分取得

String date = "2012-10-10
date.substring(0, 4); // 2012
date.substring(5, 7); // 10
date.substring(8, 10); // 10

置換

String str = "hogeaiueo";
System.out.println(str.replace("hoge", "piyo")); // piyoaiueo
System.out.println(str.replaceFirst("hoge", "piyo")); // piyoaiueo // 初回見つけた1つだけ置換
tags = tags.replaceAll("ttps://example.com/v1/event", "ttps://hoge.com/hogehoge/v1/event"); // すべて変更

特殊文字を置換

String str = "aiu[hoge]eo";
url = url.replaceFirst("\\[hoge\\]", "hogehoge"); // aiuhogehogeeo

エンコード・デコード

import java.net.URLEncoder;
try {
    Log.i("test", URLEncoder.encode("[aiueo]", "UTF-8")); // %5Baiueo%5D
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
import java.net.URLDecoder;
try {
    Log.i("test", URLDecoder.decode("%5Baiueo%5D", "UTF-8")); // [aiueo]
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

文字列検索

String str = "aiueohogeaiueo";
String searchstr = "hoge";    
if (str.indexOf(searchstr) != -1) {
    System.out.println("hit");
} else {
    System.out.println("no hit");
}