Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
If a have for example:
nem
ava
ma
Output would be:
nam eva ma
This is My code:
class Message {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("String without white spaces:");
String str = s.next();
str.replaceAll("\\s+", "");
if (str.length() <= 81) {
System.out.println("in range");
} else {
System.out.println("out of range");
}
gridStr(str);
}
static void gridStr(String str) {
int l = str.length();
int k = 0, row, column;
row = (int) Math.floor(Math.sqrt(l));
column = (int) Math.ceil(Math.sqrt(l));
if (row * column < l) {
row = column;
}
char s[][] = new char[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (k < str.length())
s[i][j] = str.charAt(k);
k++;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (s[i][j] == 0) {
break;
}
System.out.print(s[i][j]);
}
System.out.println("");
}
}
}
This shows only answers for first element of string but not all code for matrix.
You could do it like this using streams.
split the string on spaces to create an array.
stream a large number of ints for string indices
for each of those, stream the array
if the index is less than the length of the streamed string, get the character at that index. Otherwise, return an empty string.
join into a string.
and continue doing so until the returned string is empty.
String str = "nem ava ma";
String[] strs = str.split("\\s+");
String[] result = Stream.iterate(0, i->++i)
.map(i -> Arrays.stream(strs)
.map(s -> i < s.length() ?
s.substring(i, i + 1) : "")
.collect(Collectors.joining()))
.takeWhile(s -> !s.isEmpty()).toArray(String[]::new);
for (String r : result) {
System.out.println(r);
}
prints
nam
eva
ma
And here is one way of doing it using for loops
// create an array of the words as before.
String str = "nem ava ma";
String[] strs = str.split("\\s+");
// generate an unlimited number of potential columns
for (int col = 0;; col++) {
// allocate a StringBuilder in which to build the string
StringBuilder sb = new StringBuilder();
// iterate thru the array of strings and append the
// character at the current column. If the col is equal to the string
// length, don't append anything.
for (String s :strs) {
if (col < s.length()) {
sb.append(s.charAt(col));
}
}
// if the stringBuilder is empty, then no more strings
// can be built so break out of the loop
if (sb.isEmpty()) {
break;
}
// otherwise, print the string.
System.out.println(sb.toString());
}
Related
I am working on a small project, and it's mostly working out. The whole purpose is to take a file loop through it, and each individual line gets delimited in some manner. I've done that for commas, pipes, etc, but I also need to do a fixed width version. I wrote the code below, which should take find all the elements on the line isolate only the ones with a string value, and add it to an arrayList.
Right now it adds the first value, and then a series of commas to represent the whitespace, but it never gets to the 2nd string value.
public static List fwListCreator(String str) throws IOException {
List<String> fixedWidthList = new ArrayList<String>();
char[] charArray = str.toCharArray();
List<List<Boolean>> zeroWhite = new ArrayList<>();
zeroWhite.add(new ArrayList<Boolean>());
List<Boolean> temp = zeroWhite.get(0);
//add all non-whitespace character from string
for (char ch : charArray) {
temp.add(!Character.isWhitespace(ch));
}
System.out.println(temp);
//get all nonwhitespace characters per column
int maxLine = zeroWhite.stream().mapToInt(e -> e.size()).max().orElse(0);
System.out.println(maxLine);
//max number of characters in row.
int[] charCountArray = new int[maxLine];
//counting all non-whitespace per column
for (List<Boolean> row : zeroWhite) {
for (int columnChars = 0; columnChars < row.size(); ++columnChars) {
if (row.get(columnChars)) {
++charCountArray[columnChars];
}
}
}
//overview of non-white columns
Map<Integer, Long> potentialMap = (Map<Integer, Long>) Arrays.stream(charCountArray).mapToObj(i -> (Integer)i).collect(Collectors.groupingBy( Function.identity(), // their identity (value)
Collectors.counting()));
//minimum number of non-whitespace columns
int emptyIntVal = Collections.min(potentialMap.keySet());
//find delimited columns
List<Boolean> emptyListVal= Arrays.stream(charCountArray).mapToObj(n -> n == emptyIntVal).collect(Collectors.toList());
List<Integer> valIndices = new ArrayList<>();
for (int charCount = 0; charCount < maxLine; ++charCount) {
if (emptyListVal.get(charCount)) {
valIndices.add(charCount);
}
}
System.out.println(valIndices);
int indexSizeVal = valIndices.size();
valIndices.add(0,0);
int len = str.length();
//parse
for (int i = 1; i <= indexSizeVal; ++i) {
if (len < valIndices.get(i)) break;
fixedWidthList.add(str.substring(valIndices.get(i-1), valIndices.get(i)).trim());
}
return fixedWidthList
}
These are the 3 lines being passed in the file, 1 each time so str represents 1 of these lines at a time.
Ackerman Scott
Jones Steve
Gaiman Neil
Is this what you were looking for? I don't have any idea what your data source is so I just used a String[][]
public static String format(String[][] columns){
int[] maxSize = new int[columns[0].length];
for (int i = 0; i < maxSize.length; i++) {
int max = 0;
for (String[] column : columns) {
max = Math.max(max, column[i].length());
}
maxSize[i] = max;
}
StringBuilder sb = new StringBuilder();
for (String[] column : columns) {
for (int i = 0; i < column.length; i++) {
sb.append(String.format("%-" + maxSize[i] + "s", column[i]));
}
sb.append("\n");
}
return sb.toString();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Got a String like:
String str = "###############";
Got guess word, for example:
String guess = "Java"
User must guess word:
User input:
Sava
Sring should be:
String str = "#a#a###########";
all right symbols placed on their indexes
String is immutable class.
I chose Stringbuilder
for (int i = 0; i < length ; i++) {
if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
sb.append(rnd.charAt(i));
}
}
System.out.println(sb);
sb.delete(0, sb.length());
Stringbuilder add right symbols not on possition 'i', but on the last indexes.
Example:
guess word: Java
user input Sala:
System.out.println(sb);
###############aa
How I can achieve needed result?
And what tools should I use?
needed result:
Example:
guess word Java:
user input Sala:
System.out.println(sb);
#a#a###########
Work like this:
private static String word(){
String guess = new Scanner(System.in).nextLine();
return guess;
}
private static void guessWord(String[]arr) {
int random = new Random().nextInt(arr.length);
String rnd = arr[random];
int length = 15;
StringBuilder sb = new StringBuilder();
String guess = "";
int rndLength = length - rnd.length();
int guessLength = length - guess.length();
do {
System.out.println("Enter a word: ");
guess = word();
if (sb.length() < length){
for (int i = 0; i < length ; i++) {
sb.append("#");
}
}
for (int i = 0; i < length && i < rnd.length() && i < guess.length(); i++) {
if (rnd.charAt(i) == guess.charAt(i)){
sb.setCharAt(i, rnd.charAt(i));
sb.delete(length, sb.length());
}
}
if (rnd.equals(guess)){
System.out.println("Guess word: " + rnd);
break;
}else if (!rnd.equals(guess)) {
System.out.println(sb);
}
}while (!rnd.equals(guess));
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
String str = "#a#a###########";
String guess = "Java";
String input = "Sala";
StringBuilder sb = new StringBuilder();
int i;
for (i = 0; i < str.length() && i < guess.length() && i < input.length(); i++) {
// In case of a match, append the matched character
if (guess.charAt(i) == input.charAt(i)) {
sb.append(guess.charAt(i));
} else {// Else append the placeholder symbol from `str`
sb.append(str.charAt(i));
}
}
// Append the remaining placeholder characters from `str`
sb.append(str.substring(i));
// Display
System.out.println(sb);
}
}
Output:
#a#a###########
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
As per my code, I ask user to enter a string. I want to convert it in 2 dimensional array of NXN size. Although N can be variable but for now considering it to be 3. I want to format the string inputted by the user as below.
For input string :
⌐Φ┼╨¡¬╨┴╨
I want to arrange like this way.
[⌐ Φ ┼
╨ ¡ ¬
╨ ┴ ╨]
Below is the code.
public static void main(String[] args) {
Map<Character,Character> inputMap = new HashMap<Character,Character>();
inputMap.put('a', '|');
inputMap.put('b', 'β');
inputMap.put('c', '⌐');
inputMap.put('d', '≡');
inputMap.put('e', '╨');
inputMap.put('f', 'Ω');
inputMap.put('g', '╟');
inputMap.put('h', '¬');
inputMap.put('i', '↔');
inputMap.put('j', 'Σ');
inputMap.put('k', '¥');
inputMap.put('l', '╒');
inputMap.put('m', '┼');
inputMap.put('n', '«');
inputMap.put('o', 'Φ');
inputMap.put('p', '╔');
inputMap.put('q', 'Є');
inputMap.put('r', '┴');
inputMap.put('s', 'δ');
inputMap.put('t', '╬');
inputMap.put('u', '┤');
inputMap.put('v', 'θ');
inputMap.put('w', '●');
inputMap.put('x', '◙');
inputMap.put('y', 'σ');
inputMap.put('z', '∞');
inputMap.put(' ', '¡');
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
char arr[]=new char[myData.length()];
arr=myData.toCharArray();
for(int i = 0; i < arr.length; i++) {
arr[i]=inputMap.get(arr[i]);
System.out.println( arr[i]);
}
}
how can I do this?
There is a method in String.java toCharArray(). This will give you single dimensional array. Now iterate it using simple for loop. In each iteration you can print the character and at each Nth iteration print a new line.
public static void main(String[] args) {
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
ins.close();
char [] oneDArray = myData.toCharArray();
int N = 3; // or you can set it by asking the user
char[][] twoDArray = new char[N][N];
int size = oneDArray.length;
boolean isEndReached = false;
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
int index = row*N + col;
if(index >= size){
isEndReached = true;
break;
}
twoDArray[row][col] = oneDArray[index];
}
if(isEndReached){
break;
}
}
//printing...
System.out.print("[");
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
System.out.print(twoDArray[row][col]+" ");
}
System.out.println();
}
System.out.print("]");
}
Hope this helps...
You can print blank line at certain interval, e.g.:
String[] array = new String[10];//your map
int n = 5;
int count = 0;
for(String element : array){
count++;
System.out.print(element + " ");
if(count%n == 0){
System.out.println();
}
}
This question already has answers here:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
(22 answers)
Closed 7 years ago.
convert string to camelCase
eg:
"user_id" to "userId"
"user_name" to "userName"
"country_province_city" to "countryProvinceCity"
how to do that in a easy way?
ps:"country_province_city" should be "countryProvinceCity" not "countryprovincecity"
I would use a loop and a StringBuilder. Something like
String[] arr = { "user_id", "user_name", "country_province_city" };
for (String str : arr) {
StringBuilder sb = new StringBuilder(str);
int pos;
while ((pos = sb.indexOf("_")) > -1) {
String ch = sb.substring(pos + 1, pos + 2);
sb.replace(pos, pos + 2, ch.toUpperCase());
}
System.out.printf("%s = %s%n", str, sb);
}
And I get the (requested)
user_id = userId
user_name = userName
country_province_city = countryProvinceCity
As Fast Snail mentions, simply use, for example, if String str = "user_id, user_name, user_id";, call str = str.replaceAll("userID", "user_id");, causing str to now have the value "userID, user_name, userID"
Alternatively, a more complete method would be as follows
public String toCamel(String str) {
String[] splits = str.split("_");
for (int i = 1; i < splits.length; i++) {
char first = Character.toUpperCase(splits.charAt(0));
if (splits[i].length() > 0)
splits[i] = first + splits[i].substring(1);
else
splits[i] = first + "";
}
String toRet = "";
for (String s : splits)
toRet += s;
return toRet;
}
This is a very simple one:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String result = "";
String input = scan.nextLine();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '_') {
result += input.toUpperCase().charAt(i + 1);
i = i + 1;
} else {
result += input.toLowerCase().charAt(i);
}
}
System.out.println(result);
}
if you like to do it many times, I advice you to use a while loop to keep repeating the same code over and over again:
while (true) {
//the previous code
}
http://commons.apache.org/proper/commons-lang/javadocs/api-3.4/index.html
String str="country_province_city";
wordUtils.capitalize(str, '_');
str=str.replaceAll("_", "");
output: countryProvinceCity
For another point of view that the answers above you can also do it with split function and two loops, like this:
String[] strings = {"user_id","user_name","country_province_city"};
for (int i = 0; i < strings.length; i++)
{
String string = strings[i];
String totalString = "";
String[] divide = string.split("_");
for(int j = 0; j < divide.length; j++)
{
if(j != 0)
{
divide[j] = "" + divide[j].toUpperCase().charAt(0) + divide[j].substring(1,divide[j].length());
}
totalString = totalString + divide[j];
}
}
If you want to show this changed Strings by console you just have to add System.out.println after the second loop and inside the first one, like this:
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
System.out.println(totalString);
}
On the contrary, if your objective it's to store them into an array, you can do it like this:
String[] store;
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
store = new String[divide.length];
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
store[j] = totalString;
}
If you have any doubt about the code please let me know.
I expect it will help to you!
I am trying to implement a custom split string method and I am getting lost in for loops. I will post my code so far and hopefully someone can tell me where I am going wrong. I know there are better ways to do this, but I am just wondering why I can't seem to get the for loops to read properly. Basically I want to be able to set multiple delimiters at once. So I was populating a an array of just the delimiters and trying to compare each character in the full string with each entry in the delimiter Array. If it was not a delimiter, it added it to a string, if it was, it broke off the loop and took the string it created and added it to the first entry in the string array. This should continue until the character array was done.
Here is my code:
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
String[] delimArray = new String[regex.length()];
// Fill array with delimiter values
for (int i=0; i < delimArray.length; i++) {
delimArray[i] = Character.toString(regex.charAt(i));
}
// Fill array with all values in string by character
for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}
for (int i=0; i < stringArray.length; i++) {
String s1 = "";
for (int k=0; k < charArray.length; k++) {
for (int j=0; j < delimArray.length; j++) {
if (charArray[k] != delimArray[j]) {
s1 = s1 + charArray[k];
} else if (charArray[k] == delimArray[j]) {
stringArray[i+1] = delimArray[j];
break;
}
}
s1 = s1 + charArray[k];
}
stringArray[i] = s1;
}
Try this-
public static String[] split(String string, String delem) {
ArrayList<String> list = new ArrayList<String>();
char[] charArr = string.toCharArray();
char[] delemArr = delem.toCharArray();
int counter = 0;
for (int i = 0; i < charArr.length; i++) {
int k = 0;
for (int j = 0; j < delemArr.length; j++) {
if (charArr[i+j] == delemArr[j]) {
k++;
} else {
break;
}
}
if (k == delemArr.length) {
String s = "";
while (counter < i ) {
s += charArr[counter];
counter++;
}
counter = i = i + k;
list.add(s);
//System.out.println(" k = "+k+" i= "+i);
}
}
String s = "";
if (counter < charArr.length) {
while (counter < charArr.length) {
s += charArr[counter];
counter++;
}
list.add(s);
}
return list.toArray(new String[list.size()]);
}
Try this:-
String regex = "";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// If the current character is a delimiter then donot add it to the final string array result
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
EDITED ANSWER:-
String s = "ab#12#45-3";
System.out.println(s.matches("\\d+"));
String regex = "-#";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// Else block is reached when any of the character in the string is a delimiter
// Check if the current array position is null(which means nothing is assigned so far) and move to the next position only if it is not null
if(stringArray[i] != null) {
i++;
}
// Assign the delimiter in the output array
stringArray[i] = Character.toString(s.charAt(k));
// Increment to the next position in the array
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
/*
* To avoid nulls in the final split array we need to initialize one more array
* and assign only valid values to the final split array
*/
String[] splitStrArr = new String[i+1];
int m = 0;
do {
splitStrArr[m] = stringArray[m];
m++;
} while (m <= i);