Convert comma separated string to array without string split? - java

Using Java, how would I convert "Paul, John, Ringo" to
Paul
John
Ringo
But while using a loop that searches for the commas and pulls out the words between them? I can't use anything like string split, strictly a loop and pretty simple java. Thanks!

String str = "Paul, John, Ringo";
List<String> words = new ArrayList<String>();
int cIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
String temp = str.substring(cIndex, i).trim();
cIndex = i + 1;
words.add(temp);
}
}
String temp = str.substring(str.lastIndexOf(',')+1,str.length()).trim();
words.add(temp);

List<String> list = new List<String>();
String text = "your, text, here";
int indexTraversed = 0;
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
}
String[] array = list.toArray();
and if you can't use List :
String[] list = new String[100];
int counter = 0;
String text = "your, text, here";
int indexTraversed = 0; // declaring and assigning var
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
counter ++;
}
Then read the list array until counter.

Related

Finding Count of Pattern in a String (Overlap Inclusive)

So I'm trying to write an algorithm that counts the number of occurrences of some pattern, say "aa", within a string, say "aaabca." The number of patterns in that string should return an integer, in this case 2, because the first three characters contain two occurrences of the pattern.
What I have finds the number of patterns under the assumption the existing occurrences of a pattern is NOT overlapping:
public class Pattern{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string: ");
String s = scan.nextLine();
String[] splittedInput = s.split(";");
String pattern = splittedInput[0];
String blobs = splittedInput[1];
Pattern p = new Pattern();
p.count(pattern, blobs);
}
public static void count(String pattern, String blobs){
String[] substrings = blobs.split("[|]");
int numOccurences = 0;
int[] instances = new int[substrings.length];
int patternLength = pattern.length();
for (int i = 0; i < instances.length; i++){
int length = substrings[i].length();
String temp = substrings[i];
temp = temp.replaceAll(pattern, "");
int postLength = temp.length();
numOccurences = (length - postLength) / pattern.length();
instances[i] = numOccurences;
numOccurences = 0;
}
int sum = 0;
for (int i = 0; i < instances.length; i++){
System.out.print(instances[i] + "|");
sum += instances[i];
}
System.out.print(sum);
}
}
Any suggestions?
I would personally compare the pattern as a substring in this case. For example a run of a single String from your array would look like this:
//Initial values
String blobs = "aaaabcaaa";
String pattern = "aab";
String[] substrings = blobs.split("[|]");
//The code I added that should placed into the loop
int numOccurences = 0;
String str = substrings[0];
for (int k = 0; k <= (str.length() - pattern.length()); k++)
{
if (str.substring(k, k + pattern.length()).equals(pattern))
{
numOccurences++;
}
}
System.out.println(numOccurences);
If you want to run this on each String in your array simply modify String str = substrings[0] to String str = substrings[i] and iterate over the array storing the final numOccurences as you please.
Example Run:
String is aaaabcaaa
Pattern is aa
Output is 5 occurences
For one String, match is the String you're looking for:
int len = theStr.length ();
int start = 0;
int pos;
int count = 0;
while ((start < len) && ((pos = theStr.indexOf (match, start)) >= 0))
{
++count;
start = pos + 1;
}
If you use Java 8 you can count this value in the following way.
Example:
String blobs = "aaabcaaa";
String pattern = "aa";
List<String> strings = Arrays.asList(blobs.split(""));
long count = IntStream.range(0, strings.size())
.mapToObj(index -> index < strings.size() - 1 ? strings.get(index) + strings.get(index + 1) : strings.get(index - 1))
.filter(str -> str.equals(pattern))
.count();
System.out.println("Result count: " + count);
Continually taking substrings and using the startsWith method seems to work pretty well.
String pat = "ss";
String str = "kskslsksaaaslsslssskssssllsssss";
int count = 0;
while (str.length() >= pat.length()) {
count += str.startsWith(pat) ? 1 : 0;
str = str.substring(1);
}
System.out.println("count = " + count);
You can also take a similar approach with streams.
long count = IntStream.range(0, str.length()).mapToObj(
n -> str.substring(n)).filter(n -> n.startsWith(pat)).count();
System.out.println("count = " + count);
But in this case I actually prefer the non-stream approach.

Reformat a String array

I would like to re-format a String array based on condition. Say, the array
A = ["samsung", "chargers", "fast", "charging", "rapid", "high"]
int index = 1
Which means I will adjoin the items till index 1 with space and format the array. So, finally, it will be,
A = ["samsung chargers", "fast", "charging", "rapid", "high"]
For the index = 2, the output should be,
A = ["samsung chargers fast", "charging", "rapid", "high"]
I write the code that works, I try to find more concise (but not low performance) way.
StringBuilder builder = null;
..........
int fCount = ...
// format the array to match the string
// values = ["samsung", "chargers", "fast", "charging", "rapid", "high"]
builder = new StringBuilder();
String formated = "";
for (int i = 0; i <= fCount; i++) {
builder.append(values[i]).append(" ");
}
formated = builder.toString().trim();
String[] fVaues = new String[values.length - fCount];
fVaues[0] = formated;
for (int i = 1; i < fVaues.length; i++) {
fVaues[i] = values[i+1];
}
What is the simple way to accomplish it?
This method does the same thing:
static String[] joinUntil(String[] original, int until) {
return Stream.concat(
Stream.of(String.join(" ", Arrays.copyOf(original, until))),
Arrays.stream(Arrays.copyOfRange(original, until, original.length))
).toArray(String[]::new);
}
private static List<String> reFormat(List<String> lst, int index){
String joined = String.join(" ", lst.subList(0, index + 1));
List<String> res = new ArrayList<String>();
res.add(joined);
res.addAll(lst.subList(index + 1, lst.size()));
return res;
}
You could just loop over it, adding the Strings to a second array:
String[] b = new String[a.length - index];
String tmp = a[0];
for(int i = 1; i < a.length; i++) {
if(i <= index) {
tmp += " " + a[i];
if(i == index) {
b[i - index] = tmp;
}
}
else {
b[i - index] = a[i];
}
}

How to convert reminder int value to string (Characters)

How to convert int value into string means my string will be 42646 character its mod 42600 how to show and print this character and how?
int count = image_length.length(); //count=42646
System.out.println(count);
int mod = count % length; //46
int rem = count - mod; //42600
String rem_value = String.valueOf(rem);
// I want to get string through reminder value 42600 & how
String[] split = rem_value.split("[^a-zA-Z/]", length);
getSaltString();
photoName = randStr + "_IMG.jpg";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < split.length; i++) {
url_part = String.valueOf(stringBuilder.append(split[i]));
new RegisterImageThread(ActivityRegisterUploadPhoto.this).execute(photoName, url_part + i);
}
new RegisterImageThread(ActivityRegisterUploadPhoto.this).execute(photoName, url_part+rem_value);
So you want to split the numeric String "42600" to an array right?
Replace the line:
String[] split = rem_value.split("[^a-zA-Z/]", length);
to something like this:
String rem_value = "42600"; //your rem_value
int[] split = new int[rem_value.length()];
for (int i = 0; i < rem_value.length(); i++) {
split[i] = Character.getNumericValue(rem_value.charAt(i));
}
//print the result
Arrays.stream(split).forEach(s -> System.out.println(s));

My findCombos method does not work, How to remove characters from java character array

I am making a method which will return a String[] containing valid combinations of words that differ by one letter. The method takes as String array containing a dictionary of words as the first parameter, and two other strings containing the words one and two respectively as the second and third parameters.
Here is my method:
public static String[] findCombos(String[] dict, String a, String b){
char[] wordA = a.toCharArray();
char[] wordB = b.toCharArray();
int length = wordA.length;
List<String> validCombos = new ArrayList<String>();
Arrays.sort(dict);
//wordA
for(int i = 0; i<length; i++){
char tmp = wordA[i];
wordA[i] = 0;
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString().trim();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
int lengthb = wordB.length;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString();
for(int j = 0; j<lengthb; j++){
tmpWordB = new StringBuffer(tmpWordB).insert(j ,tmp).toString();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordA[i] = tmp;
}
}
}else{
wordA[i] = tmp;
}
}
//wordB
int lengthb = b.length();
for(int i = 0; i<lengthb; i++){
char tmp = wordB[i];
wordB[i] = 0;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString().trim();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
int lengtha = a.length();
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString();
for(int j = 0; j< lengtha; j++){
tmpWordA = new StringBuffer(tmpWordA).insert(j, tmp).toString();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordB[i] = tmp;
}
}
}else{
wordB[i] = tmp;
}
}
String[] res = validCombos.toArray(new String[0]);
return res;
}
The array has been sorted and I am certain that the element in question is in the array, however the search keeps returning a negative number and automatically branching to the else clause. Any ideas? Here is a link to the dictionary:
Dictionary - PasteBin
You are not removing the character at index i, you are replacing the character at index i with 0, that false assumption breaks your algorithm.
Delete a character by index from a character array with StringBuilder
String mystring = "inflation != stealing";
char[] my_char_array = mystring.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(mystring);
sb.deleteCharAt(10);
my_char_array = sb.toString().toCharArray();
System.out.println(my_char_array); //prints "inflation = stealing"
The above code removes the exclamation mark from the character array.
Roll your own java function to remove a character from a character array:
String msg = "johnny can't program, he can only be told what to type";
char[] mychararray = msg.toCharArray();
mychararray = remove_one_character_from_a_character_array_in_java(mychararray, 21);
System.out.println(mychararray);
public char[] remove_one_character_from_a_character_array_in_java(
char[] original,
int location_to_remove)
{
char[] result = new char[original.length-1];
int last_insert = 0;
for (int i = 0; i < original.length; i++){
if (i == location_to_remove)
i++;
result[last_insert++] = original[i];
}
return result;
}
//The above method prints the message with the index removed.
Source:
https://stackoverflow.com/a/11425139/445131

How to Split an Array

I'm trying to figure out how to split an array into smaller sections. I have an String array with a bunch of characters. I would like to make a new array that stores the first five of those characters in it's first index, the next five in the next index, etc..
Something like this?
String separator = new String("|");
String [] splits = string.split(separator);
Assuming you have something like this:
String[] myArray = {"12345123", "45123", "45"};
You can split it into an array of five characters like this:
String wholeString="";
for(String s : myArray)
wholeString += s;
int arrayLength = wholeString.length()/5;
if(wholeString.length()%5==0)
arrayLength--;
String[] arrayOfFive = new String[arrayLength];
int counter=0;
String buffer = "";
for(int i=0;i<s.length();i++){
buffer += s.charAt(i);
if(buffer.length()==5){
arrayOfFive[counter] = buffer;
buffer = "";
}
Now, if you don't want to get the whole array string into memory and hold it there, you can do this one character at a time:
String buffer = "";
List<String> stringList = new ArrayList<String>();
for(String s : myArray){
for(int i=0;j<s.length();i++){
buffer += s.charAt(i);
if(buffer.length()==5){
stringList.add(buffer);
buffer = new String();
}
}
}
String[] arrayOfFive = new String[stringList.length()];
stringList.toArray(arrayOfFive);
If you simply have an array of 1-character strings, then you can do it like this:
int arrayLength = myArray.length/5;
if(myArray.length%5==0)
arrayLength--;
String[] arrayOfFive = new String[arrayLength];
for(int i=0;i<myArray.length;i++){
if(i%5==0)
arrayOfFive[i/5] = "";
arrayOfFive[i/5] += myArray[i];
}
If you have a string array containing a single string of length 500, then you can get the string like this:
String myString = myArray[0];
After which you can loop through the characters in the string, breaking it up:
for(int i=0;i<myString.length();i++){
if(i%5==0)
arrayOfFive[i/5] = "";
arrayOfFive[i/5] += myString.charAt(i);
}
List<String> list=new ArrayList<String>();
int chunkSize=5;
for (int i=0; i<strings.size; i++) {
int lastChunk = strings[i].length() % chunkSize;
int chunks=strings[i].length() / chunkSize;
for (int j=0; j<chunks; j++) {
list.add(strings[i].substring(j*chunkSize,j*chunkSize+chunkSize);
}
if (lastChunk > 0) {
list.add(strings[i].substring(chunks*chunkSize, chunks*chunkSize+lastChunk);
}
}
char c[]=str.toCharArray();
int array_length=0;
int start=1;
if(str.length()%5==0)
{
array_length=str.length()/5;
}
else
array_length=str.length()/5 +1;
String s[]=new String[array_length];
for(int i=0;i<array_length;i++)
{
String temp="";
for(int j=start;j<=str.length();j++)
{
if(j%5==0)
{
temp=temp+c[j-1];
start=j+1;
break;
}
else
{
temp=temp+c[j-1];
}
}
s[i]=temp;
}
for(int i=0;i<array_length;i++)
{
System.out.println(s[i]);
}

Categories

Resources