我有一个字符串(基本上是一个遵循命名约定的文件名) abc.def.ghi
我想在第一个之前提取子字符串.(即一个点)
在java doc api中,我似乎无法在String中找到一个方法.
我错过了什么吗?怎么做?
Sam*_*m B 96
接受的答案是正确的,但它没有告诉你如何使用它.这是您一起使用indexOf和substring函数的方法.
String filename = "abc.def.ghi"; // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "."
//in string thus giving you the index of where it is in the string
// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found.
//So check and account for it.
String subString;
if (iend != -1)
{
subString= filename.substring(0 , iend); //this will give abc
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ins 81
你可以拆分字符串..
public String[] split(String regex)
Run Code Online (Sandbox Code Playgroud)
请注意,java.lang.String.split使用分隔符的正则表达式值.基本上这样......
String filename = "abc.def.ghi"; // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots
String beforeFirstDot = parts[0]; // Text before the first dot
Run Code Online (Sandbox Code Playgroud)
当然,这被分为多个线条用于clairity.它可以写成
String beforeFirstDot = filename.split("\\.")[0];
Run Code Online (Sandbox Code Playgroud)
Max*_*ann 62
如果您的项目已经使用了commons-lang,StringUtils为此提供了一个很好的方法:
String filename = "abc.def.ghi";
String start = StringUtils.substringBefore(filename, "."); // returns "abc"
Run Code Online (Sandbox Code Playgroud)
Ume*_*yat 11
或者你可以尝试类似的东西
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
使用正则表达式怎么样?
String firstWord = filename.replaceAll("\\..*","")
Run Code Online (Sandbox Code Playgroud)
这将用“”替换从第一个点到结尾的所有内容(即清除它,留下你想要的东西)
这是一个测试:
System.out.println("abc.def.hij".replaceAll("\\..*", "");
Run Code Online (Sandbox Code Playgroud)
输出:
abc
Run Code Online (Sandbox Code Playgroud)
小智 5
我尝试过这样的事情,
String str = "abc.def.ghi";
String strBeforeFirstDot = str.substring(0, str.indexOf('.'));
// strBeforeFirstDot = "abc"
Run Code Online (Sandbox Code Playgroud)
我尝试以我的示例为例,提取@登录电子邮件之前的所有字符以提取并提供用户名。
| 归档时间: |
|
| 查看次数: |
290975 次 |
| 最近记录: |