Java 从逗号分隔的字符串中获取第一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22644746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting first value from a comma separated string
提问by user264953
I have a string in the following format"
我有以下格式的字符串"
String s = name1, name2, name3, name4, name5,name6;
字符串 s = 姓名 1、姓名 2、姓名 3、姓名 4、姓名 5、姓名 6;
What is the best way out to get name1 out of this sing a generic solution which can be applied to a similar comma separated string?
从这个唱出一个通用解决方案中获得 name1 的最佳方法是什么,它可以应用于类似的逗号分隔字符串?
Any help is appreciated.
任何帮助表示赞赏。
回答by Christian
You can use the split()
method. It returns an array String[]
, so you can access to an element by using the syntax someArray[index]
. Since you want to get the firstelemnt, you can use [0]
.
您可以使用该split()
方法。它返回一个数组String[]
,因此您可以使用语法访问元素someArray[index]
。由于您想获得第一个元素,因此可以使用[0]
.
String first_word = s.split(",")[0];
Note:
笔记:
- Indices in most programming languages start with
0
. So the first elemnt will be in the index0
. The second in the index1
. So on.
- 大多数编程语言中的索引以
0
. 所以第一个元素将在 index 中0
。索引中的第二个1
。很快。
回答by SirTyler
String first = s.split(",")[0];
That should work perfectly fine for you.
这对你来说应该很好。
回答by Jose Martinez
s.split(",")[0];
Split gives you an array of Strings that are split up by the regex provided in the argument. You would want to check the length of the output of the split before using it.
Split 为您提供由参数中提供的正则表达式拆分的字符串数组。在使用拆分之前,您可能需要检查其输出的长度。
回答by Junaid Hassan
String parts[]=s.split(",");
String part1=parts[0];
Use like this if you want to get the first name
如果您想获得名字,请像这样使用
回答by nimsson
If you look at String.split(String regrex), you will find that it will return an array of strings.
如果您查看String.split(String regrex),您会发现它将返回一个字符串数组。
name1 = s.split(", ")[0];
The [0]
is the first index in an array, so it will be your name1. s.split(", ").length
is equal to the size of the array, so if you ever need any index s.split(", ")[num-1]
where num
is the number of the index you want starting at one.
该[0]
是一个数组的第一个索引,所以这将是您的姓名1。s.split(", ").length
等于数组的大小,所以如果你需要任何索引s.split(", ")[num-1]
,num
你想要从 1 开始的索引数在哪里。