java 如何将字符串分成相等的部分并将其存储在字符串数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26114025/
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
How to split a string into equal parts and store it in a string array
提问by Nagash
I'm fairly new to Java and am stuck on a particular homework question where a String gets passes and from there I have to split it into parts equal to an Integer that was passed.
我对 Java 还很陌生,并且被困在一个特定的作业问题上,其中 String 被传递,然后我必须将它分成与传递的 Integer 相等的部分。
For example: String "HelloWorld" is input and it has to be divided by 2 and those parts then have to be put into an array that has two parts like: array[hello, world].
例如:输入字符串“HelloWorld”,它必须除以 2,然后必须将这些部分放入一个由两部分组成的数组,例如:array[hello, world]。
Is there anyway to do this using a FOR loop?
有没有办法使用 FOR 循环来做到这一点?
My code so far enters the whole String into each array element. Here is my code:
到目前为止,我的代码将整个 String 输入到每个数组元素中。这是我的代码:
String[] splitIntoParts(String word, int size) {
String[] array = new String[size];
for (int i = 0; i < array.length; i++) {
array[i] = word;
println(array[i]);;
}
return array;
}
回答by christopher
First check if the length of the string is a multiple of the divisor:
首先检查字符串的长度是否是除数的倍数:
if(str.length() % divisor == 0)
Then you know that you can grab equal chunks of it. So you use substring
to pull them out, in a loop.
然后你知道你可以抓住它的相等块。所以你substring
习惯把它们拉出来,在一个循环中。
while(str.length() > 0) {
String nextChunk = str.substring(0,divisor);
// store the chunk.
str = str.substring(divisor,str.length());
}
Will cycle through and grab a chunk that is divisor
long each time.
divisor
每次都会循环并抓取一个很长的块。
回答by Jonathan Solorzano
There are many ways:
有很多方法:
Here's the regex version:
这是正则表达式版本:
public void splitEqual(String s){
int length = s.length();//Get string length
int whereToSplit;//store where will split
if(length%2==0) whereToSplit = length/2;//if length number is pair then it'll split equal
else whereToSplit = (length+1)/2;//else the first value will have one char more than the other
System.out.println(Arrays.toString(s.split("(?<=\G.{"+whereToSplit+"})")));//split the string
}
\G
is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \A.
The enclosing lookbehind matches the position that's four characters along from the end of the last match.
\G
是一个零宽度断言,匹配前一个匹配结束的位置。如果没有前一个匹配,它匹配输入的开头,与\A.
封闭的lookbehind匹配从最后一个匹配的结尾开始的四个字符的位置相同。
Both lookbehind and \G are advanced regex features, not supported by all flavors. Furthermore, \G
is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma).
lookbehind 和 \G 都是高级正则表达式功能,并非所有风格都支持。此外,\G
在支持它的风格中并没有一致地实现。这个技巧可以在(例如)Java、Perl、.NET 和 JGSoft 中工作,但不能在 PHP (PCRE)、Ruby 1.9+ 或 TextMate(都是 Oniguruma)中工作。
Using Substring:
使用子串:
/**
* Split String using substring, you'll have to tell where to split
* @param src String to split
* @param len where to split
* @return
*/
public static String[] split(String src, int len) {
String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
for (int i=0; i<result.length; i++)
result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
return result;
}
You should also check this answer: Google Guava split
您还应该检查这个答案:Google Guava split
回答by Piyush Jajoo
This is not plagarism, formatted the answer mentioned here - https://stackoverflow.com/a/3761521as per the question.
这不是剽窃,按照问题格式化了这里提到的答案 - https://stackoverflow.com/a/3761521。
public static void main(String[] args){
String str = "HelloWorld";
int parts = str.length()/3;
System.out.println(Arrays.toString(
str.split("(?<=\G.{"+parts+"})")
));
}
回答by Dhanushka Gayashan
Try the following application.It is dividing the provided word into equal parts based on the provided size per part
尝试以下应用程序。它根据提供的每个部分的大小将提供的单词分成相等的部分
public class WordSpliter {
public static void main(String[] args) {
String[] words = new WordSpliter().splitter("abcdefghij", 4);
for(String s : words) System.out.println(s);
}
private String[] splitter(String word, int size) {
// Decide the size of the String array
int rest = word.length() % size;
int arrSize = ((word.length() - rest) / size) + 1;
// Declare the array and the start point of the word
String[] words = new String[arrSize];
int startPoint = 0;
for (int i = 0; i < words.length; i++) {
if (i + 1 == words.length) {
words[i] = word.substring(startPoint, startPoint + rest);
} else {
words[i] = word.substring(startPoint, startPoint + 4);
startPoint += 4;
}
}
return words;
}
}
}
Good Luck !!!!
祝你好运 !!!!
回答by Ruchira Gayan Ranaweera
Just looking at your input HelloWorld
, You are trying to substring your input by Upper case letter.
只看您的输入HelloWorld
,您正试图用大写字母对您的输入进行子串。
You should go with that.
你应该这样做。
String str = "HelloWorldUser";
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
String temp = (str.charAt(i) + "").toUpperCase();
if (temp.equals(str.charAt(i) + "")) { // check for upper case letters
indexList.add(i);
}
}
List<String> subStrings = new LinkedList<>(); // to keep the insertion order
for (int i = indexList.size() - 1; i > -1; i--) { // substring reverse order
subStrings.add(str.substring(indexList.get(i)));
str=str.substring(0,indexList.get(i));
}
Collections.reverse(subStrings); // reverse to get original order
System.out.println(subStrings);
Out put:
输出:
[Hello, World, User]
If you want to get final result in to an array you can use
如果你想得到一个数组的最终结果,你可以使用
String[] arr= subStrings.toArray(new String[subStrings.size()]);
回答by Kick Buttowski
Since length of a string is dived by 2
由于字符串的长度被 2
Code:
代码:
String st ="HelloWorld";
String firstPart = "";
String secondPart = "";
for (int j = 0; j < st.length(); j++) {
if ( j < st.length() /2) {
firstPart += st.charAt(j);
}else
secondPart += st.charAt(j);
}
System.out.println(firstPart);
System.out.println(secondPart);
Output:
输出:
Hello
World
Explanation: you add to firstPart String as long as your index has not met the middle index of the String. When it passed the middle index of String, you make the secondPart
说明:只要您的索引未满足字符串的中间索引,您就添加到 firstPart 字符串。当它通过 String 的中间索引时,你做第二部分
回答by Rohit
You can use Brute force
你可以使用蛮力
public static List<String> splitStringEqually(String text, int size)
{
List<String> result = new ArrayList<String>((text.length() + size - 1) / size);
for (int i = 0; i < text.length(); i += size) {
result.add(text.substring(i, Math.min(text.length(), i + size)));
}
return result;
}
回答by mujeeb.omr
String s = "HelloWorld";
String firts_part=(String) s.subSequence(0, s.length() / 2);
String second_part=(String) s.subSequence((s.length() / 2)+1,s.length()-1 );
Try subSequence();
尝试 subSequence();
回答by Nagash
I figured it out. Here is my code:
我想到了。这是我的代码:
String[] array = new String[size];
char[] charArray = new char[length(word)];
char[] temp = new char[length(word) / size];
int place = 0;
// turn the string into an array of chars
for (int i = 0; i < charArray.length; i++) {
charArray[i] = getChar(word, i);
}
// loop for each element of the desired string array
for (int i = 0; i < array.length; i++) {
// fill a temp array with the correct characters and the corect amount of characters
for (int j = 0; j < charArray.length / size; j++) {
temp[j] = charArray[place];
++place;
}
// insert the temp array into each element of the string array
array[i] = new String(temp);
}
return array;
回答by RIPAN
A Simple solution is like
一个简单的解决方案就像
static void split(String str, int n) {
int partSize = str.length() / n;
while (str.length() - partSize > 0) {
String s = str.substring(0, partSize-1);
System.out.print(s + " ");
str = str.substring(partSize-1);
}
if (str.length() > 0) {
System.out.print(str);
}
}