I'm getting a string from the web looking like this:
Latest Episode#04x22^Killing Your Number^May/15/2009
Then I need to store 04x22, Killing Your Number and May/15/2009 in diffent variables, but it won't work.
String[] all = inputLine.split("#");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);
Now it only stores NextNr, with the whole string
04x22^Killing Your Number^May/15/2009
What is wrong?
String.split(String regex)
The argument is a regualr expression, and ^ has a special meaning there; "anchor to beginning"
You need to do:
String[] need = all[1].split("\\^");
By escaping the ^ you're saying "I mean the character '^' "
If you have a separator but you don't know if it contains special characters you can use the following approach
String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);
Using guava, you can do it elegantly AND fast:
private static final Splitter RECORD_SPLITTER = Splitter.on(CharMatcher.anyOf("#^")).trimResults().omitEmptyStrings();
...
Iterator<String> splitLine = Iterables.skip(RECORD_SPLITTER.split(inputLine), 1).iterator();
show.setNextNr(splitLine.next());
show.setNextTitle(splitLine.next());
show.setNextDate(splitLine.next());
public static String[] split(String string, char separator) {
int count = 1;
for (int index = 0; index < string.length(); index++)
if (string.charAt(index) == separator)
count++;
String parts[] = new String[count];
int partIndex = 0;
int startIndex = 0;
for (int index = 0; index < string.length(); index++)
if (string.charAt(index) == separator) {
parts[partIndex++] = string.substring(startIndex, index);
startIndex = index + 1;
}
parts[partIndex++] = string.substring(startIndex);
return parts;
}
String input = "Latest Episode#04x22^Killing Your Number^May/15/2009";
//split will work for both # and ^
String splitArr[] = input.split("[#\\^]");
/*The output will be,
[Latest Episode, 04x22, Killing Your Number, May/15/2009]
*/
System.out.println(Arrays.asList(splitArr));
Related
I have to write a method which breaks a string into groups. The user should give the amount of letters per group and the function should return a string that consists of the input string broken into groups. For instance, function(“HELLOYOU”, 2) would return “HE LL OY OU”.
You can use String.split() to break the string into an array of individual letters, and then combine pairs of letters, or larger groups, etc.
Here is some example code:
String[] splitInParts(String input, int size) {
String[] letters = input.split("");
String[] output = new String[letters / size];
for (int i = 0; i < output.length; i++) {
output[i] = "";
for (int j = 0; j < size; j++) {
output[i] = output[i] + letters[size * i + j];
}
}
return output;
}
There is a lot of boilerplate code missing, for example, checking that loop parameters are in range, checking strings are not null, etc. However this is a rough idea of how you could go about doing it.
You can move the characters of input String to a new String and put whitespaces on every step that equals to "size":
String function(String input, int parts) {
StringBuilder result = new StringBuilder();
int partCounter = 0;
for (int i = 0; i < input.length(); i++) {
partCounter++;
result.append(input.charAt(i));
if (partCounter == parts){
result.append(" ");
partCounter = 0;
}
}
return result.toString();
}
You could use the below code that takes in a String instance and aN int defining the number of characters to split based on. And then use the String instances split method.
public static String[] split(String input, int len){
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return null;
}
// Split the input string based on a regex pattern
return input.split(String.format("(?<=\\G.{%1$d})", len));
}
The Regular Expression that is being used here is (?<=\\G.{%1$d}) which based on len being 2 would become (?<=\\G.{2}). So this means it would split every 2 characters. So the output for a string of HELLOWORLD would be HE, LL, OW, OR, LD .
If you wanted to join those into one String separated by a space you could using the StringUtils#join method.
String joinedString = StringUtils.join(split, StringUtils.SPACE);
Which would produce "HE LL OW OR LD".
So an all in one method would be:
public static String separateNthCharacter(String input, int len) {
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return StringUtils.EMPTY;
}
String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));
return StringUtils.join(split, StringUtils.SPACE);
}
I get an error for String[] t = words.split("_"); using jdk 1.3 in intelliJ
Error:(133, 51) java: cannot find symbol
symbol: method split(java.lang.String)
location: variable words of type java.lang.String
I have to use this SDK because the project is old, I tried jdk 1.4 but had many other errors, then I decided to replace the above code with something that can be complied using jdk 1.3.
What is the function for that?
The following piece of code seems to be working fine for me.
However, I have assumed that the delimiter on the basis of which you need to split is only a single character.
public static void main(String[] args){
String string = ",alpha,beta,gamma,,delta";
String[] wordsSplit = splitByDelimiter(string, ",");
for(int i=0; i<wordsSplit.length; i++){
System.out.println("-"+wordsSplit[i]+"-");
}
}
public static String[] splitByDelimiter(String fullString, String delimiter){
// Calculate number of words
int index = 0;
int[] delimiterIndices = new int[fullString.length()];
int wordCount = 0;
do{
if(delimiter.equals(fullString.charAt(index)+"")){
delimiterIndices[wordCount++] = index;
}
index++;
} while(index < fullString.length());
// Correction for strings not ending in a delimiter
if(!fullString.endsWith(delimiter)){
delimiterIndices[wordCount++] = fullString.length();
}
// Now create the words array
String words[] = new String[wordCount];
int startIndex = 0;
int endIndex = 0;
for(int i=0; i<wordCount; i++){
endIndex = delimiterIndices[i];
words[i] = fullString.substring(startIndex, endIndex);
startIndex = endIndex+1;
}
return words;
}
Alternate solution:
public static ArrayList splitByDelimiter(String fullString, String delimiter){
fullString += delimiter; //
ArrayList words = new ArrayList();
int startIndex = 0;
int endIndex = fullString.indexOf(delimiter); //returns first occurence
do{
words.add(fullString.substring(startIndex, endIndex));
startIndex = endIndex+1;
endIndex = fullString.indexOf(delimiter, startIndex);
} while(endIndex != -1);
return words;
}
public String[] split(String regex) was introduced in Java 1.4
So you could use your own implementation using StringTokenizer(String str, String delim) which was introduced in Java 1.0
List list = new ArrayList();
StringTokenizer st = new StringTokenizer("this_is_a_test", "_");
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
//[this, is, a, test]
Further if you want final result as an Array, you can use
String[] t = list.toArray(new String[0]);
You will either have to use StringTokenizer, a combination of indexOf() and substring(), or something you make on your own.
You could go with the C approach, which is: implement it yourself.
Here is a possible implementation, it now returns all elements, might need some tweaks:
int length;
int split_amount = 0;
String temp = new String("This_takes_into_consideration_something_something_test");
char split = '_';
for(int i = 0; i<length;i++){
if(temp.charAt(i) == split ){
split_amount++;
}
}
split_amount++;
String[] result = new String[split_amount];
int j = 0;
for(int i = 0; i<split_amount; i++){
result[i] = "";
boolean t = true;
for(; j<length && t ;j++){
if(temp.charAt(j) == split){
t = false;
break;
}
result[i] += temp.charAt(j);
}
j++;
}
Maybe a simple solution is:
String words = "this_is_a_test";
StringTokenizer st0 = new StringTokenizer(words, "_");
String[] t = new String[st0.countTokens()];
int k = 0;
while(st0.hasMoreTokens()){
String tmp0 = st0.nextToken();
t[k] = tmp0;
k++;
}
Lets say I have a string "aabbccaa". Now I want to replace occurrences of "aa" in given string by another string. But it should be in following way.
First occurrence of "aa" should be replaced by "1" and next occurrence of "aa" by "2" and so on.
So, the result of the string becomes "1bbcc2".
You can use replaceFirst() in a for loop where counter is incrementing...
for (int i = 1; string.contains("aa"); i++) {
string = string.replaceFirst("aa", "" + i);
}
You can do it using the Matcher's appendReplacement method:
Pattern p = Pattern.compile("aa");
Matcher m = p.matcher("aabbccaahhhaahhhaaahahhahaaakty");
StringBuffer sb = new StringBuffer();
// Variable "i" serves as a counter. It gets incremented after each replacement.
int i = 0;
while (m.find()) {
m.appendReplacement(sb, ""+(i++));
}
m.appendTail(sb);
System.out.println(sb.toString());
This approach lets you avoid creating multiple string objects (demo).
It is possible to do using Java functions but using a char array and doing it using a lower level of logic would be faster.
String s = "aabbccaa";
String target = "aa";
int i = 1;
String newS;
for (int j = 0; j < s.length; j++) {
newS = s.replaceFirst(target, i++);
j += newS.length - s.length;
s = newS;
}
Here is a solution :
public static void main(String[] a) {
int i = 1;
String before = "aabbccaabbaabbaa";
String regex = "aa";
String after = substitute(i, before, regex);
System.out.println(after);
}
private static String substitute(int i, String before, String regex) {
String after = before.replaceFirst(regex, Integer.toString(i++));
while (!before.equals(after)) {
before = after;
after = before.replaceFirst(regex, Integer.toString(i++));
}
return after;
}
Output :
1bbcc2bb3bb4
How we can check any string that contains any character how may time....
example:
engineering is a string contains how many times 'g' in complete string
I know this is and old question, but there is an option that wasn't answered and it's pretty simple one-liner:
int count = string.length() - string.replaceAll("g","").length()
Try this
int count = StringUtils.countMatches("engineering", "e");
More about StringUtils can be learned from the question: How do I use StringUtils in Java?
I would use a Pattern and Matcher:
String string = "engineering";
Pattern pattern = Pattern.compile("([gG])"); //case insensitive, use [g] for only lower
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
Although Regex will work fine, but it is not really required here. You can do it simply using a for-loop to maintain a count for a character.
You would need to convert your string to a char array: -
String str = "engineering";
char toCheck = 'g';
int count = 0;
for (char ch: str.toCharArray()) {
if (ch == toCheck) {
count++;
}
}
System.out.println(count);
or, you can also do it without converting to charArray: -
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == toCheck) {
count++;
}
}
String s = "engineering";
char c = 'g';
s.replaceAll("[^"+ c +"]", "").length();
Use regex [g] to find the char and count the findings as below:
Pattern pattern = Pattern.compile("[g]");
Matcher matcher = pattern.matcher("engineering");
int countCharacter = 0;
while(matcher.find()) {
countCharacter++;
}
System.out.println(countCharacter);
If you want case insensitive count, use regex as [gG] in the Pattern.
use org.apache.commons.lang3 package for use StringUtils class.
download jar file and place it into lib folder of your web application.
int count = StringUtils.countMatches("engineering", "e");
You can try Java-8 way. Easy, simple and more readable.
long countOfA = str.chars().filter(ch -> ch == 'g').count();
this is a very very old question but this might help someone ("_")
you can Just simply use this code
public static void main(String[] args){
String mainString = "This is and that is he is and she is";
//To find The "is" from the mainString
String whatToFind = "is";
int result = countMatches(mainString, whatToFind);
System.out.println(result);
}
public static int countMatches(String mainString, String whatToFind){
String tempString = mainString.replaceAll(whatToFind, "");
//this even work for on letter
int times = (mainString.length()-tempString.length())/whatToFind.length();
//times should be 4
return times;
}
You can try following :
String str = "engineering";
int letterCount = 0;
int index = -1;
while((index = str.indexOf('g', index+1)) > 0)
letterCount++;
System.out.println("Letter Count = " + letterCount);
You can loop through it and keep a count of the letter you want.
public class Program {
public static int countAChars(String s) {
int count = 0;
for(char c : s.toCharArray()) {
if('a' == c) {
count++;
}
}
return count;
}
}
or you can use StringUtils to get a count.
int count = StringUtils.countMatches("engineering", "e");
This is an old question and it is in Java but I will answer it in Python. This might be helpful:
string = 'E75;Z;00001;'
a = string.split(';')
print(len(a)-1)
I have a large stringbuffer which i would like to break into smaller parts. The string buffer looks like this
"name1+name2+name3+name4+..........+name2000"
Where
name1=john
name2=prince
and so on.
(You get the idea.name1,name2,name3 stand for actual names of varying length)
Now i would like to store the names in a string array with each positon containing a 200 names.
string[0]="name1+name2+name3+........+name200";
string[1]="name201+name202+...."
How would i go about achieving this task?
StringTokenizer str = new StringTokenizer(<StringBufferObject>);
int count = 0;
int arrCount = 0;
StringBuffer temp;
String[] stringArr = new String[x];
while(str.hasMoreTokens()) {
count++;
if(count != 200) {
temp.append(str.nextToken());
}
else {
stringArr[arrCount] = temp;
temp.delete(0,temp.length());
count = 0;
arrCount++;
}
It would be a lot easier to split a String using String.split() if that's possible:
/* something like this */
String arrayOfStrings = inputString.split("\+");
If you have to keep it as a StringBuffer you'll have to loop over the input and tokenize it yourself.
I guess it would look something like this:
public String[] getTwoHundredStrings(StringBuffer inputBuff, String someToken)
{
String [] nameArray = new String [200];
int currentPos = 0;
int nextPos = 0;
for ( int i = 0; i < 200; i ++ ) {
nextPos = inputBuff.indexOf(someToken, currentPos);
if ( nextPos < 0 ) {
break;
}
String nextName = inputBuff.substring(currentPos, nextPos);
nameArray[i] = nextName;
currentPos = nextPos;
}
/* do some cleanup if nameArray has less than 200 elements */
return nameArray;
You must have some delimiter between each name. To break the string we should have some delimiter.
If you have delimiter you can use subString() in for loop.
try to use
String[] tempNames = new String(namesBuffer).split("+");
and then
int length = (tempNames.length / 200)+ (tempName.length % 200)
String[] names = new String[length];
for(int i = 0 ; i< tempNames.length ; i++){
for(int j = 0 ; j < length ; j++)
names[j] = tempNames[i];
}
hope this helps
Split on "+", using String.split("\\+")
Get chucks, in smaller arrays, Arrays.copyOfRange(...)
Join using Guava Joiner like Joiner.on("+").join(smallerArray)