I'm working on a study problem from class and essentially it reads a string, and a character. The character is the delimiter. It will then search the string for the delimiter and create an array in equal length to the number of times the delimiter is found. It then assigns each character or string to its own spot in the array and returns it.
Maybe I am over thinking things, but the just of it is to not rely on the various string methods and to sort of create your own. How can I get this method to only assign the string/char found in the one that is read to one position in the array and not all as well as stop it from adding unnecessary output? Help/Suggestions greatly appreciated
public static String[] explode(String s, char d){
String []c;
int count = 1;
//checks to see how many times the delimter appears in the string and creates an array of corresponding size
for(int i = 0; i < s.length(); i++){
if(d == s.charAt(i))
count ++;
}
c = new String [count];
//used for checking to make sure the correct number of elements are found
System.out.println(c.length);
//goes through the the input string "s" and checks to see if the delimiter is found
//when it is found it makes c[j] equal to what is found
//once it has cycled through the length of "s" and filled each element for c, it returns the array
for(int i = 0; i < s.length(); i++){
for(int j = 0; j < c.length; j++){
if(d == s.charAt(i))
c[j] += s.substring(i-1);
}
}
//provides output for the array [c] just to verify what was found
for(int y = 0; y < c.length; y++)
System.out.println(c[y]);
return c;
}
public static void main(String [] args){
String test = "a,b,c,d";
char key = ',';
explode(test,key);
}
^The following will output:
4
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
I'm aiming for:
4
a
b
c
d
Thank you
Perhaps you could try something like this:
public static void main(String[] args){
explode("a,b,c,d", ',');
}
public static void explode(final String string, final char delimiter){
int length = 1;
for(final char c : string.toCharArray())
if(delimiter == c)
length++;
if(length == 1)
return;
final String[] array = new String[length];
int index, prev = 0, i = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
array[i++] = string.substring(prev, index);
prev = index+1;
}
array[i] = string.substring(prev);
System.out.println(length);
for(final String s : array)
System.out.println(s);
}
Output of the program above is:
4
a
b
c
d
Or if you want to utilize a List<String> instead (and Java 8), you could remove a couple of lines by doing something like this:
public static void explode(final String string, final char delimiter){
final List<String> list = new LinkedList<>();
int index, prev = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
list.add(string.substring(prev, index));
prev = index+1;
}
list.add(string.substring(prev));
System.out.println(list.size());
list.forEach(System.out::println);
}
Related
Not sure how to set up this method which gets as parameter a String array and has to return in a new array all values that meet the following condition:
25% of characters in every element of array are numbers;
public static String[] returnSentence(String[] str){
int nrOfWords = str.length;
int count = 0;
for(int i = 0; i < nrOfWords; i++){
for(int j = 0; j < str[i].length; j++){
}
}
}
I had an idea that it should be something like this but cant format the code to test the condition...
Your question basically boils down to figuring out how many characters in the String fullfil a given condition, and how many do not.
There is two ways to do this:
1) Simply count the characters:
int numPositiveChars = 0;
int numNegativeChars = 0;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (/*check c here*/)
numPositiveChars++;
else
numNegativeChars++;
}
In fact you don't even need to count the negative chars, because that value is simply s.length() - numPositiveChars.
2) Another approach would be to use regular expressions, e.g. by removing all non-numerical characters and then get the character count:
int numPositiveChars = s.replaceAll("[^0-9]+", "").length();
This line will remove all characters from the String that are not numerical (not 0-9) and then return the length of the result (the number of characters that are numerical).
Once you have the number of chars that match your condition, calculating the percentage is trivial.
You need to just replace all non digits in each element and then compare the length like so :
public static List<String> returnSentence(String[] str) {
int nrOfWords = str.length;
List<String> result = new ArrayList<>();
for (int i = 0; i < nrOfWords; i++) {
if(str[i].replaceAll("\\D", "").length() == str[i].length() * 0.25){
result.add(str[i]);
}
}
return result; // If you want an array use : return result.toArray(String[]::new);
}
I would also use as result a List instead of array because you don't have any idea how many element is respect the condition.
If you want to solve with streaming it can be more easier :
public static String[] returnSentence(String[] str) {
return Arrays.stream(str)
.filter(s-> s.replaceAll("\\D", "").length() == s.length() * 0.25)
.toArray(String[]::new);
}
some thing like this
public static String[] returnSentence(String[] str){
int nrOfWords= str.length;
String[] temp_Str = new String[20];
int count = 0;
int k=0;
for(int i = 0;i<nrOfWords;i++){
for(int j = 0;j<str[i].length;j++){
if(Character.isAlphabetic(str[i].getcharat(j)))
{
count++;
}
if((count/100.0)*100>=25)
{ temp_Str[k]=str[i];
k++;
}
}
}
}
I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3
I'm trying to write a code which gets as an input an array of strings, and creates a two-dimensoinal array of type char, the number of lines is as the number of words in the string and in each line there is a reversed array of the letters in the word.
for example if my input is: start at the end!
my output will be :
[t, r, a, t, s]
[t, a]
[e, h, t]
[!, d, n, e]
This is my code:
public static void main(String[] args) {
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
}
}
The code should be like this :
String str ="start at the end!";
String[] splitString = str.split(" ");
int length=0;
for(String string:splitString ){
if(string.length()>length){
length=string.length();
}
}
Character[][] charArray = new Character[splitString.length][length];
int index=0;
for(String string:splitString ){
length=string.length();
for(int i=0;i<string.length();i++){
charArray[index][--length]=string.charAt(i);
}
index++;
}
for (int i=0;i<charArray.length;i++){
for (int j=0;j<charArray[i].length && charArray[i][j]!=null;j++) {
System.out.print(charArray[i][j]);
}
System.out.println();
}
OUTPUT:
trats
ta
eht
!dne
You are getting extra lines because you are printing inside the outer for loops. try this. it should work.
public static void main(String[] args) {
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
}
While editing your question I fixed indentation of your code which showed your problem clearly: you placed code responsible for printing result array in same loop which fills this array. In other words you are printing array after you add new row to it.
That is why you see results in form
[row1]
null
null
null
[row1]
[row2]
null
null
[row1]
[row2]
[row3]
null
[row1]
[row2]
[row3]
[row4]
To solve this problem simply place loop responsible for printing outside of loop responsible in generating content of result array (remember that indentation is not responsible for scoping but placement of { and } brackets is, so move one } from end before printing loop). So change your code to
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
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.
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].
Is there anyway to do this using a FOR loop?
My code so far enters the whole String into each array element. Here is my code:
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;
}
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.
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).
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
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.
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.
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 !!!!
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;
}
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();
This is not plagarism, formatted the answer mentioned here - https://stackoverflow.com/a/3761521 as per the question.
public static void main(String[] args){
String str = "HelloWorld";
int parts = str.length()/3;
System.out.println(Arrays.toString(
str.split("(?<=\\G.{"+parts+"})")
));
}
Since length of a string is dived by 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
Just looking at your input HelloWorld, You are trying to substring your input by Upper case letter.
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()]);
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;
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);
}
}
You can do it using regex as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 5)));
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 4)));
System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 2)));
}
static String[] splitIntoParts(String word, int size) {
return word.replaceAll("(.{" + size + "})", "$1\n").split("\n");
}
}
Output:
[Hello, World]
[Hell, oWor, ld]
[He, ll, oW, or, ld]
I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck