public static String[] removeCharacters(String[] arr){
String[] str = new String[arr.length];
for (int i = 0; i <arr.length; i++) {
if(Character.isLetter(arr[i].charAt(i)))
str[i] += arr[i].charAt(i);
else
str[i] = "";
}
return str;
}
I'm trying to write a method that returns to String array and takes an String array argument.
I need remove special characters from the element and return the element without specials.
For example;
["Hel123&$$o", "#$%World", "###"]
will return to
["Hello", "World", "",] as a output.
I also converted back to String, remove those special characters and split back again to an Array but when i convert to String it all comes together and there is no split point and I don't want to do it with Regex so i'm trying to do without it. With my solution I'm getting null so i couldn't fix.
Here's a changed version. You have to use a nested for loop - the first iterates over the input String[] and the nested one over the char[] in each string.
I have also used some variables in place of repeated array references for easy reading.
public class StrArray{
public static void main( String[] args ){
String[] input = new String[]{ "Hel123&$$o", "#$%World", "###" };
String[] strArr = removeCharacters( input );
Arrays.stream( strArr ).forEach( s -> System.out.println( "'" + s + "'" ) );
}
public static String[] removeCharacters( String[] arr ){
String[] str = new String[ arr.length ];
for( int i = 0; i < arr.length; i++ ){
String input = arr[ i ];
/* If the input string in empty, skip.*/
int k = 0;
if( input == null || input.length() == 0 )
str[ i ] = "";
else{
/* Construct a char[] containing all the relevant chars. */
char[] chars = new char[ input.length() ];
for( int j = 0; j < input.length(); j++ ){
char c = input.charAt( j );
if( Character.isLetter( c ) ) chars[ k++ ] = c;
}
/* Now, convert the char[] into a string. */
str[ i ] = String.valueOf( chars, 0, k );
}
}
return str;
}
}
I have quoted each string while printing. Hence, running this gives the following output.
'Helo'
'World'
''
The problem is that you are iterating over the array of strings but not over the array of characters of each string. You can use a loop to iterate over the array of Strings and a nested loop to iterate over the characters of each String.
Here I'm using StringBuilder to concatenate the Strings since it is more efficient than using +. This is because the String object is immutable, so each call for concatenation will create a new String object. On the other hand, StringBuilder is a mutable array of characters.
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
String[] stringArray =
new String[]{ "Hell123&$$o", "#$%World", "###" };
System.out.println(
Arrays.toString(removeCharacters(stringArray)));
}
public static String[] removeCharacters(String[] arr) {
String[] str = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
StringBuilder strBuilder = new StringBuilder();
for (int j = 0; j < arr[i].length(); j++) {
if (Character.isLetter(arr[i].charAt(j)))
strBuilder.append(arr[i].charAt(j));
}
str[i] = strBuilder.toString();
}
return str;
}
}
Related
public static void reverse(String[] array){
String reverse = "";
for(int i=0;i<array.length;i++){
for(int j = array[i].length() - 1; j >= 0; i--)
{
reverse = reverse + array[i].charAt(i);
}
}
}
Using this method I am trying to reverse every single string in the string array but it just throws an exception. The array's length and elements are being inputed with scanner.
public static String[] arrayStringCreation(String[] array){
boolean isArrayInputStillGoing = true;
while (isArrayInputStillGoing){
System.out.println();
System.out.println("Input the size of the array");
int sizeOfArray = scanner.nextInt();
if (sizeOfArray <= 0){
System.err.println("Size can't be less than 1");
continue;
}
array = new String[sizeOfArray+1];
System.out.println("Input words less than 20 symbols");
for(int i=0;i<sizeOfArray+1;i++){
array[i] = scanner.nextLine();
if (array[i].length()>20){
System.err.println("Try again with a word with less than 20 symbols");
i--;
}
}
isArrayInputStillGoing=false;
}
return array;
}
StringBuilder::reverse
Simply iterate the array, and replace each entry with its reverse. You can use a StringBuilder to reverse a String, calling StringBuilder.reverse.
Like,
public static void reverse(String[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = new StringBuilder(array[i]).reverse().toString();
}
}
And then to test it
public static void main(String[] args) {
String arr[] = { "abc", "def" };
reverse(arr);
System.out.println(Arrays.toString(arr));
}
See this code run live at IdeOne.com.
[cba, fed]
Stream
The Answer by Elliott Frisch is correct and robust, and should be accepted.
In addition, for fun, here is a version of that code using streams rather than the conventional for loop. I am not claiming this is better.
I do not know of a way for a stream of an array to affect that array. So instead here I make and return a fresh array.
public static String[] reverse( String[] array ) {
Objects.requireNonNull( array , "Received null argument where an array of `String` was expected. Message # b5c03336-4b9e-4735-a054-16e43aac059e.") ;
Stream< String > stream = Arrays.stream( array ) ;
String[] result =
stream
.map( ( String s ) -> new StringBuilder( s ).reverse().toString() )
.toArray(String[]::new)
;
return result ;
}
Usage.
String arr[] = { "abc" , "def" , "mask😷" } ;
String arr2[] = Ideone.reverse( arr ) ;
System.out.println( Arrays.toString( arr ) ) ;
System.out.println( Arrays.toString( arr2 ) ) ;
See that code run live at IdeOne.com.
[abc, def, mask😷]
[cba, fed, 😷ksam]
You can use StringUtils.reverse of org.apache.commons.lang3 from the Apace Commons project. That method handles null.
public static void reverse(String[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = StringUtils.reverse(array[i]);
}
}
You didn't update the array with the reverse string and decrement j in the inner loop
public static void reverse(String[] array) {
String reverse;
for (int i = 0; i < array.length; i++) {
reverse = "";
for (int j = array[i].length() - 1; j >= 0; j--) {
reverse += array[i].charAt(j);
}
array[i] = reverse;
}
}
, main
public static void main(String[] args) {
String arr[] = { "head", "body", "hand" };
reverse(arr);
System.out.println(Arrays.toString(arr));
}
, output
[daeh, ydob, dnah]
Here is another option. It will work in most versions of Java. Instead of returning a new Array, it simply modifies the one that is passed.
public class ReverseStringsInArray {
public static void main(String[] args) {
String [] strArr = {"alpha", "beta","gamma","delta"};
reversed(strArr);
for (String v : strArr) {
System.out.println(v);
}
}
public static void reversed(String[] arr) {
int k = 0;
for (String v : arr) {
int[] s = v.codePoints().toArray();
int len = v.length();
// swap the outer characters as the pointer moves
// towards the middle
for (int i = 0; i < len >> 1; i++) {
int cp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = cp;
}
arr[k++] = new String(s,0,s.length);
}
}
}
I have a string array for example:
new String[] = {"powerhouse", "p, pow, power, house, pose, poser"};
My goal is to split the first entry in the array in this case powerhouse into any two words and check them against the second entry, which serves as a dictionary of words.
Here's my implementation so far:
public static String[] convertWordsToArray(String input){
String[] wordArr = null;
wordArr = input.split(",");
return wordArr;
}
public static String splitEm(String[] strArr) {
String fw = strArr[0];
String sw = strArr[1];
String[] arrOne = convertWordsToArray(fw);
System.out.println(arrOne.length);
String[] dict = convertWordsToArray(sw);
System.out.println(dict.length);
for(int i = 0; i < dict.length - 1; i++) {
String mWord = fw.split(i, i + 1);
System.out.println(mWord);
}
// Edit Starts Here, tried to substring it but nothing prints in log
for(int i = 0; i < arrOne.length; i++) {
String mWord = fw.substring(0, i);
System.out.println(mWord);
}
return ""; // empty for now
}
I am stuck at the part where the first word has to be split. Should I use two loops, one for the first word and the other for the dictionary? I know that somehow the dictionary has to be converted to a list or array list to avail the .contains() method. How do I go about this? Thanks.
If anyone want the solution for PHP language, then you can use below code:
function ArrayChallenge($strArr) {
$dictWords = explode( ',', $strArr[1] );
$strLength = strlen($strArr[0]);
$output = 'not possible';
for( $i = 1; $i < $strLength; $i++ ){
$firstStr = substr($strArr[0], 0, $i);
$lastStr = substr($strArr[0], $i, $strLength);
if ( in_array( $firstStr, $dictWords ) && in_array( $lastStr, $dictWords ) ) {
$output = $firstStr . ',' . $lastStr;
break;
}
}
return $output;
}
Do you need something like this?
String s = "powerhouse";
List<String> list = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
for(int j = i+1; j <= s.length(); j++){
list.add(s.substring(i,j));
}
}
System.out.println(list);
I assume you need something like below:
Split second string at each , or even better using regex to trim
spaces before or after ,
check if each part of the splited entry fro above point is made of
only the chars contained in the first entry of your input
example
public static void main(String args[]) {
String[] test1 = {"powerhouse", "p, pow, power, house, pose, poser"};
String[] test2 = {"powerhouse", "p, xyz, power, house, pose, poser"};
System.out.println(check(test1));
System.out.println(check(test2));
}
static boolean check(String[] input){
String firstEntry = input[0];
String[] dictionary = input[1].split("\\s*,\\s*");
for(int i = 0; i < dictionary.length; i++){
if(!dictionary[i].matches("["+firstEntry+"]+")){
return false;
}
}
return true;
}
this will print true for the first case and false for the second as "xyz" is not a valid subpart/substring according to your discription
Try this :
public class Stack {
public static void main(String[] args) {
String[] str = {"powerhouse", "p, pow, power, house, pose, poser"};
String firstPart = str[0];
String secondPart = str[1];
boolean contain = isContain(firstPart, secondPart);
System.out.println(contain);
}
private static boolean isContain(String firstPart, String secondPart) {
for (int i = 0; i < firstPart.length(); i++) {
String firstWord = firstPart.substring(0, i);
String secondWord = firstPart.substring(i, firstPart.length());
List<String> strings = Arrays.asList(secondPart.trim().split("\\s*,\\s*"));
if (strings.contains(firstWord) && strings.contains(secondWord)) return true; if you want to check both words use this
//if (strings.contains(firstWord) || strings.contains(secondWord)) return true; if you want to check any(one) word from two words use this
}
return false;
}
}
I'm trying to figure out how to take a array of Characters that spell out a sentence backwards (or out of order) with the words separated by spaces to distinguish them and re-order them in the correct/reversed format so instead of the character array spelling out World Good Hello it would spell out Hello Good World like this ['H','e','l','l','o',' ','G','o','o','d',' ','W','o','r','l','d']
This is more or less a shot in the dark.
In the end I would like to return it back as an array of characters.
Code:
class Main {
public static void main(String[] args) {
// World Good Hello
// reverse to: Hello Good World
char[] chrArray = new char[] {'W','o','r','l','d',' ','G','o','o','d',' ','H','e','l','l','o'};
String str = String.valueOf(chrArray);
String[] strArray = str.split(" ");
char[] result = new char[0];
for (int i = 0; i < strArray.length; i++) {
for (int h = 0; h < strArray[i].length(); h++) {
char[] temp = new char[strArray[i].charAt(h)];
temp[temp.length - 1] = ' ';
char[] both = Arrays.copyOf(result, result.length);
List<character> temp2 = System.arraycopy(temp, 0, both, result.length, temp.length);
result = temp2.toCharArray();
}
}
}
}
public static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder buf = new StringBuilder(sentence.length());
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
Use reverseWords(...).toCharArray() to get char array.
I think the following code would be enough to reverse:
String[] strArray = str.split(" ");
for(int i =strArray.length-1;i>=0;i--) {
System.out.print(strArray[i] + " ");
}
this will output : Hello Good World
I want to create a static method Static String displayArray (int [] array) that takes an integer array as parameter, uses a loop to create and return a new String that represents the contents of the array surrounded by braces and separated by commas.
For example,
int [] myArray = { 12,9,10,25};
String str = displayArray(myArray);
System.out.println (str); // should display {12,9,10,25}
My solution:
public static String displayArray (int [] array) {
for (int i=0; i< array.length; i++) {
System.out.println(array[i]);
}
return null;
}
But it gives output as follows:
12
9
10
25
null
You need to build a String object to return. Right now you are returning null, which is literally nothing.
I'd suggest using a StringBuilder, it's a little faster than concatenating Strings directly. So before your loop you'll want to define a StringBuilder object and add the opening brace:
StringBuilder returnString = new StringBuilder();
returnString.append("{");
Then within your loop, you can concatenate each number:
returnString.append(Integer.toString(array[i]);
After that you'll want to make a check to see if you have the last element, if not, append a comma.
Finally append the closing brace, and instead of return null use:
return returnString.toString();
You might need this:
public static String displayArray(int[] array) {
StringBuilder builder = new StringBuilder("{");
for (int i = 0; i < array.length; i++) {
builder.append((array[i])).append(",");
}
return builder.substring(0, builder.length() - 1).concat("}");
}
Something like this:
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
for (int i=0; i< array.length; i++) {
sb.append(array[i]);
if(i!=array.length-1)
sb.append(",");
}
return "{"+sb.toString()+"}";
}
Yes, exactly it is giving you the right output.
To get your desired output you can modify your display array function as follow:
public static String displayArray (int [] array) {
String str = "";
for (int i=0; i< array.length; i++) {
str += array[i]+",";
}
returns str;
}
public static String displayArray( int[] array )
{
return "{" + Arrays.toString( array ).replace("[", "").replace("]", "") + "}";
}
Going off of #BorisTheSpider idea and because I find this easier than Stringbuilder, here is your method to return the string { val1, val2, val3 }.
Basically, print out your braces manually and replace the brackets with "".
Do this instead:
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
for (int i=0; i< array.length; i++) {
sb.append(array[i]+",");
}
String result=sb.toString()+",";
result=result.replace(",,","");
return "{"+result+"}";
}
None of the answers display the output like you wanted it.
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
sb.append("{");
for (int i=0; i< array.length; i++) {
sb.append(array[i]);
if(i != array.length-1)
sb.append(",");
}
sb.append("}");
return sb.toString();
}
I've been really struggling with a programming assignment. Basically, we have to write a program that translates a sentence in English into one in Pig Latin. The first method we need is one to tokenize the string, and we are not allowed to use the Split method usually used in Java. I've been trying to do this for the past 2 days with no luck, here is what I have so far:
public class PigLatin
{
public static void main(String[] args)
{
String s = "Hello there my name is John";
Tokenize(s);
}
public static String[] Tokenize(String english)
{
String[] tokenized = new String[english.length()];
for (int i = 0; i < english.length(); i++)
{
int j= 0;
while (english.charAt(i) != ' ')
{
String m = "";
m = m + english.charAt(i);
if (english.charAt(i) == ' ')
{
j++;
}
else
{
break;
}
}
for (int l = 0; l < tokenized.length; l++) {
System.out.print(tokenized[l] + ", ");
}
}
return tokenized;
}
}
All this does is print an enormously long array of "null"s. If anyone can offer any input at all, I would reallllyyyy appreciate it!
Thank you in advance
Update: We are supposed to assume that there will be no punctuation or extra spaces, so basically whenever there is a space, it's a new word
If I understand your question, and what your Tokenize was intended to do; then I would start by writing a function to split the String
static String[] splitOnWhiteSpace(String str) {
List<String> al = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
if (Character.isWhitespace(ch)) {
if (sb.length() > 0) {
al.add(sb.toString());
sb.setLength(0);
}
} else {
sb.append(ch);
}
}
if (sb.length() > 0) {
al.add(sb.toString());
}
String[] ret = new String[al.size()];
return al.toArray(ret);
}
and then print using Arrays.toString(Object[]) like
public static void main(String[] args) {
String s = "Hello there my name is John";
String[] words = splitOnWhiteSpace(s);
System.out.println(Arrays.toString(words));
}
If you're allowed to use the StringTokenizer Object (which I think is what the assignment is asking, it would look something like this:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
which will produce the output:
this
is
a
test
Taken from here.
The string is split into tokens and stored in a stack. The while loop loops through the tokens, which is where you can apply the pig latin logic.
Some hints for you to do the "manual splitting" work.
There is a method String#indexOf(int ch, int fromIndex) to help you to find next occurrence of a character
There is a method String#substring(int beginIndex, int endIndex) to extract certain part of a string.
Here is some pseudo-code that show you how to split it (there are more safety handling that you need, I will leave that to you)
List<String> results = ...;
int startIndex = 0;
int endIndex = 0;
while (startIndex < inputString.length) {
endIndex = get next index of space after startIndex
if no space found {
endIndex = inputString.length
}
String result = get substring of inputString from startIndex to endIndex-1
results.add(result)
startIndex = endIndex + 1 // move startIndex to next position after space
}
// here, results contains all splitted words
String english = "hello my fellow friend"
ArrayList tokenized = new ArrayList<String>();
String m = "";
int j = 0; //index for tokenised array list.
for (int i = 0; i < english.length(); i++)
{
//the condition's position do matter here, if you
//change them, english.charAt(i) will give index
//out of bounds exception
while( i < english.length() && english.charAt(i) != ' ')
{
m = m + english.charAt(i);
i++;
}
//add to array list if there is some string
//if its only ' ', array will be empty so we are OK.
if(m.length() > 0 )
{
tokenized.add(m);
j++;
m = "";
}
}
//print the array list
for (int l = 0; l < tokenized.size(); l++) {
System.out.print(tokenized.get(l) + ", ");
}
This prints, "hello,my,fellow,friend,"
I used an array list since at the first sight the length of the array is not clear.