String array conversion does not work - arrays

I have written this sub to convert the a date in the format 20140101 to 01/01/2014. From the variable inDate I decided to load this into the array arrDate. Each element of the array is correct. It is when I try and put the array back into a string (outDate) I get the following result.
indate=20140101 outDate=97/01/2014
indate=20140202 outDate=98/02/2014
Can anyone say why?
Thanks,
Lawrence
private String convDate (String inDate) {
String outDate = "XXXXXXXXXX";
char[] arrDate = inDate.toCharArray();
switch (MainActivity.localloc){
case "E":
System.out.println("posO "+arrDate[0]);
System.out.println("pos1 "+arrDate[1]);
System.out.println("pos2 "+arrDate[2]);
System.out.println("pos3 "+arrDate[3]);
System.out.println("pos4 "+arrDate[4]);
System.out.println("pos5 "+arrDate[5]);
System.out.println("pos6 "+arrDate[6]);
System.out.println("pos7 "+arrDate[7]);
outDate=arrDate[6]+arrDate[7]+"/"+ arrDate[4]+arrDate[5]+"/"+arrDate[0]+arrDate[1]+arrDate[2]+arrDate[3];
}
return outDate;
}

private void Button2_Click(System.Object sender, System.EventArgs e)
{
string str = null;
string s = "20140101";
str = s.Substring(6, 2) + "/" + s.Substring(4, 2) + "/" + s.Substring(0, 4);
Interaction.MsgBox(str);
}

thanks for your reply. A much better way of solving my problem. I don't know what the difference is between Substring and substring is but the only way I could get it to work with substring was:
str=s.substring(6,8)+"/"+s.substring(4,6)+"/"+s.substring(0,4);
It seems substring wants the first and last character positions.
Lawrence

Related

How can I get whole string value from List in apex

I need your help.
I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want.
Here is my apex class:-
public class Assign2{
public void testFunction(String str ,integer num){
integer rem,temp = 0;
integer sumOfDigit = 0;
List<String> stringCharacters = new List<String>();
List<String> inputStr = new List<String>();
stringCharacters = str.split('');
System.debug('stringCharacters::'+stringCharacters);
for(integer i=0; i<stringCharacters.size(); i++){
if(stringCharacters[i].isNumeric()){
temp = Integer.valueOf(stringCharacters[i]);
//System.debug('temp::'+temp);
rem = temp +num;
//System.debug('rem::'+rem);
sumOfDigit = math.mod(rem,10);
//System.debug('sumOfDigit::'+sumOfDigit);
stringCharacters[i] = sumOfDigit+'';
//System.debug('ans::'+stringCharacters);
}
}
System.debug('ans::'+stringCharacters);
}}
and I run the program by giving input:-
Assign2 obj = new Assign2();
obj.testFunction('2india 234',9);
help will be appreciable.
Thank You.
You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.
List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
String word = String.join(characters, '');
System.debug(word); // "1india 123"

Splitting a text file where the information are separated in different lines

So, I have a text file where the information are separated by the enter key (I don't know how to explain, I will paste the code and some stuff).
cha-cha
Fruzsina
Ede
salsa
Szilvia
Imre
Here's how the text file looks like, and I need to split it into three parts, the first being the type of the dance, and then dancer 1 and dancer 2.
using System;
using System.Collections.Generic;
using System.IO;
namespace tanciskola
{
struct tanc
{
public string tancnev;
public string tancos1;
public string tancos2;
}
class Program
{
static void Main(string[] args)
{
#region 1.feladat
StreamReader sr = new StreamReader("tancrend.txt");
tanc[] tanc = new tanc[140];
string[] elv;
int i = 0;
while (sr.Peek() != 0)
{
elv = sr.ReadLine().Split('I don't know what goes here');
tanc[i].tancnev = elv[0];
tanc[i].tancos1 = elv[1];
tanc[i].tancos2 = elv[2];
i++;
}
#endregion
Console.ReadKey();
}
}
}
Here is how I tried to solve it, although I don't really get how I should do it. The task is would be to display the first dance and the last dance, but for that I need to split it somehow.
As mentioned in my comments, you seem to have a text file where each item is on a new line, and a set of 3 lines constitutes a single 'record'. In that case, you can simply read all the lines of the file, and then create your records, like so:
var v = File.ReadLines("file path");
tancr[] tanc = new tancr[140];
for (int i = 0; i < v.Count(); i += 3)
{
tanc[i/3].tancnev= v.ElementAt(i);
tanc[i/3].tancos1 = v.ElementAt(i + 1);
tanc[i/3].tancos2 = v.ElementAt(i + 2);
}
Note: ReadLines() is better when the file size is large. If your file is small, you could use ReadAllLines() instead.
To split by the "enter character" you can use Environment.NewLine in .NET:
https://msdn.microsoft.com/en-us/library/system.environment.newline(v=vs.110).aspx
elv = sr.ReadAllText().Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
This constant will contain the sequence that is specific to your OS (I'm guessing Windows).
You should be aware that the characters used for newlines is different for Windows vs. Linux/Unix. So in the rare event that someone edits your file on a different OS, you can run into problems.
On Windows, newline is a two character sequence: carriage-return + line-feed (ASCII 13 + 10). On Linux it is just line-feed. So if you wanted to be extra clever, you could first check for CRLF and if you only get one element back from Split() then try just LF.

How to read and add only numbers to array from a text file

I'm learning java and I have a question regarding reading from file
i want to read only numbers from file that contains strings as well.
here is an example of my file:
66.56
"3
JAVA
3-43
5-42
2.1
1
and here is my coding:
public class test {
public static void main (String [] args){
if (0 < args.length) {
File x = new File(args[0]);
try{
Scanner in = new Scanner( new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while(in.hasNext()){
if(in.hasNextDouble()){
Double f=in.nextDouble();
test.add(f);}
else
{in.next();}
}
catch(IOException e) { System.err.println("Exception during reading: " + e); }
}
my problem is it only add 66.56,2.1 and 1
it doesn't add 3 after "3 or it ignores 3-43 and 5-42
can you tell me how to skip Strings and only add doubles here?
thanks
All the said three ie; "3, 3-43 and 4-42 are strings
Either u read a string and split it and check for number at " and - or you put in a space between characters and integers.
The JVM after compilation would treat it all as string if it cannot be converted to a double.
And the File reader wont stop reading till at least a space or a newline.
Hence your code would never work the way you intend it to unless you do as I said above.
Solution 1:
Change your input file to something like this:
66.56
" 3
JAVA
3 - 43
5 - 42
2.1
1
Solution 2:
Considering the highly variable nature of your input file I am posting a solution only made for your current input. If the input changes a more versatile algorithm would need to be implemented.
public static void main(String[] args) {
File x = new File(args[0]);
try {
Scanner in = new Scanner(new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while (in.hasNext()) {
if (in.hasNextDouble()) {
Double f = in.nextDouble();
test.add(f);
} else {
String s=in.next();
if(s.contains("\"")){
String splits[]=s.split("\"");
test.add(Double.parseDouble(splits[1]));
}
else if (s.contains("-")){
String splits[]=s.split("-");
test.add(Double.parseDouble(splits[0]));
test.add(Double.parseDouble(splits[1]));
}
}
}
System.out.println(test);
} catch (IOException e) {
System.err.println("Exception during reading: " + e);
}
}
You can write custom Type Sensor Utility class to check whether the object can be converted to Integer or not. I would approach to this problem like this.
Moreover I can see that you have values like 2.1 and " 3 to handle these scenarios write additional methods like isDoubleType() or isLongType() etc.
Also you need to write some custom logic to solve this problem.
public class TypeSensor {
public String inferType(String value) throws NullValueException {
int formatIndex = -1;
if (null == value) {
throw new NullValueException("Value provided for type inference was null");
}else if (this.isIntegerType(value)) {
return "Integer";
}else{
LOGGER.info("Value " + value + " doesnt fit to any predefined types. Defaulting to String.");
return "String";
}
}
}
private boolean isIntegerType(String value) {
boolean isParseable = false;
try {
Integer.parseInt(value);
LOGGER.info("Parsing successful for " + value + " to Integer.");
isParseable = true;
} catch (NumberFormatException e) {
LOGGER.error("Value " + value + " doesn't seem to be of type Integer. This is not fatal. Exception message is->"
+ e.getMessage());
}
return isParseable;
}
}

Spacing out every 2 characters in a string?

my string is "37829300".
How can I space out every 2 characters in the string so the result can be "37 82 93 00".
I am trying to achieve this in vc++.
Thanks.
I understand I may have to use #include iostream but I am lost on how to do it properly.
Couldn't find a fancy one-liner regular-expression, so let's do it the manual way.
private static string AddSpaceAfterTwoDigits(string input)
{
string output = string.Empty;
MatchCollection arr = Regex.Matches(input, #"\d\d");
if ( arr.Count > 0 )
{
output = arr[0].Groups[0].Value; // Add the first with no space
for ( int i = 1; i < arr.Count; i++ )
{
output += " " + arr[i].Groups[0].Value;
}
}
return output;
}
The code is in C#, but it's a fairly straight-forward conversion to C++/CLI.
The code assumes an input of an even number of digits.

String Arrays and Session

I am dealing one serious problem and seems i cannot find a logical solution.
Here it goes.
I have a string array in my code (jsp file). I want to pass the array in the same page , and i thought of making the array a session and call it again later in my code but it seems that i cannot take the session (with get.Attribute) and make it an array again. TO be more specise the following code might help you.
while (onomaq.next()) {
String onomatemp = onomaq.getString("one1");
String[] onoma = onomatemp.split(" ");
out.println(onoma[2]);
session.setAttribute("onoma", onoma);
}
} catch (Exception e) {
System.out.println("SQL Exception: " + e.toString());
}
%>
<%
try{
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
out.println(name[1]);
}
catch (Exception e)
{
System.out.println("SQL Exception: " + e.toString());
}
the out.println gives me a message lige [L.java.String and some characters.
Can anyone help me please?
Rather than calling toString() on your array object after obtainig it from session, just cast the object reference to an array (since your object IS an array) and use it.
This means, replace this code:
Object o = session.getAttribute("onoma");
String k=o.toString();
String[] name=k.split(",");
with
String[] name= (String[]) session.getAttribute("onoma");
p.s. purpose of toString() is somwhat different from what you seem to expect. See Javadoc.
String[] expected_array= (String[]) session.getAttribute("onoma");
Then run it inside a loop to retrieve. Example:
for(int i = 0; i < expected_array. length; i++)
{
String strings = expected_array[i] ;
}

Resources