I need optimized solution to increment and decrement alphanumeric string value as we do in excel. When I specify alphanumeric string with range then it should give me both decremented n incremented list of values. For e.g I need range of +-10 of alphanumeric string as.
PN - Alpha character may come in start / middle /end
1. A2000018 -> A2000008 to A2000028
2. A39999 -> A39989 to A40009
3. A00005 -> A00001 to A00015
4. AZ00005 -> AZ00001 to AZ00015
5. A342S0004 -> A342S0001 to A342S0014
6. A342S9999 -> A342S9989 to A342S10009
7. 1234A -> 1224A to 1244A
8. 0003A -> 0001A to 0013A
public static List<String> getRangeList(String docNumber, int range) {
List<String> rangeList = new ArrayList<>();
System.out.println("Document Number Received " + docNumber);
/**
* REGEX checks for String value starting with 1 character as alpha and rest numeric
*/
boolean trailingAlphabet = false;
boolean leadingNtrailingAlphabet = false;
boolean leadingNtrailingNumber = false;
String patternStr = "";
if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,5}$")) { //String docNumber = "AD234SD1234 ";
patternStr = "(.*?)(\\d+)(.*?)$";
leadingNtrailingAlphabet = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,5}[0-9]{1,20}+$")) { //String docNumber = "1234AD1234 ";
patternStr = "(\\d+)(.*?)(\\d+)$";
leadingNtrailingNumber = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,4}+$")) { //String docNumber = "1234A ";
patternStr = "(\\d+)(.*?)$";
trailingAlphabet = true;
} else if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]+$")
|| docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,4}[0-9]+$")) {
patternStr = "(.*?)(\\d+)$";
}
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(docNumber.trim());
if (matcher.find()) {
String firstAlpha = "";
String origNumber = "";
String lastAlpha = "";
if (trailingAlphabet) {
firstAlpha = matcher.group(2);
origNumber = matcher.group(1);
} else if (leadingNtrailingAlphabet) {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
lastAlpha = matcher.group(3);
} else if (leadingNtrailingNumber) {
firstAlpha = matcher.group(1);
lastAlpha = matcher.group(2);
origNumber = matcher.group(3);
} else {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
}
//System.out.println("1 Alpha : " + firstAlpha + " origNNum : " + origNumber + " lastAlpha : " + lastAlpha);
String incrNumStr = origNumber;
String dcrNumStr = origNumber;
for (int i = 0; i < range; i++) {
if (Integer.parseInt(dcrNumStr) - 1 <= 0) {
break;
}
dcrNumStr = String.format("%0" + dcrNumStr.length() + "d", Integer.parseInt(dcrNumStr) - 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + dcrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + dcrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(dcrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + dcrNumStr);
}
}
for (int i = 0; i < range; i++) {
incrNumStr = String.format("%0" + incrNumStr.length() + "d", Integer.parseInt(incrNumStr) + 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + incrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + incrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(incrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + incrNumStr);
}
}
Collections.sort(rangeList);
System.out.println(rangeList);
}
return rangeList;
}
Related
I am trying the approach below. It is based on some of Uniswap's code.
I am curious as to whether it will work at reasonable cost or whether there is a better way.
function escapeHTML(string memory input)
public
pure
returns (string memory)
{
bytes memory inputBytes = bytes(input);
uint extraCharsNeeded = 0;
for (uint i = 0; i < inputBytes.length; i++) {
bytes1 currentByte = inputBytes[i];
if (currentByte == "&") {
extraCharsNeeded += 4;
} else if (currentByte == "<") {
extraCharsNeeded += 3;
} else if (currentByte == ">") {
extraCharsNeeded += 3;
}
}
if (extraCharsNeeded > 0) {
bytes memory escapedBytes = new bytes(
inputBytes.length + extraCharsNeeded
);
uint256 index;
for (uint i = 0; i < inputBytes.length; i++) {
if (inputBytes[i] == "&") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "a";
escapedBytes[index++] = "m";
escapedBytes[index++] = "p";
escapedBytes[index++] = ";";
} else if (inputBytes[i] == "<") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "l";
escapedBytes[index++] = "t";
escapedBytes[index++] = ";";
} else if (inputBytes[i] == ">") {
escapedBytes[index++] = "&";
escapedBytes[index++] = "g";
escapedBytes[index++] = "t";
escapedBytes[index++] = ";";
} else {
escapedBytes[index++] = inputBytes[i];
}
}
return string(escapedBytes);
}
return input;
}
I have to make a code that sums and subtracts two or more numbers using the + and - chars
I managed to make the sum, but I have no idea on how to make it subtract.
Here is the code (I'm allowed to use the for and while loops only):
int CM = 0, CR = 0, A = 0, PS = 0, PR = 0, LC = 0, D;
char Q, Q1;
String f, S1;
f = caja1.getText();
LC = f.length();
for (int i = 0; i < LC; i++) {
Q = f.charAt(i);
if (Q == '+') {
CM = CM + 1;
} else if (Q == '-') {
CR = CR + 1;
}
}
while (CM > 0 || CM > 0) {
LC = f.length();
for (int i = 0; i < LC; i++) {
Q = f.charAt(i);
if (Q == '+') {
PS = i;
break;
} else {
if (Q == '-') {
PR = i;
break;
}
}
}
S1 = f.substring(0, PS);
D = Integer.parseInt(S1);
A = A + D;
f = f.substring(PS + 1);
CM = CM - 1;
}
D = Integer.parseInt(f);
A = A + D;
salida.setText("resultado" + " " + A + " " + CR + " " + PR + " " + PS);
The following program will solve your problem of performing addition and subtraction in a given equation in String
This sample program is given in java
public class StringAddSub {
public static void main(String[] args) {
//String equation = "100+500-20-80+600+100-50+50";
//String equation = "100";
//String equation = "500-900";
String equation = "800+400";
/** The number fetched from equation on iteration*/
String b = "";
/** The result */
String result = "";
/** Arithmetic operation to be performed */
String previousOperation = "+";
for (int i = 0; i < equation.length(); i++) {
if (equation.charAt(i) == '+') {
result = performOperation(result, b, previousOperation);
previousOperation = "+";
b = "";
} else if (equation.charAt(i) == '-') {
result = performOperation(result, b, previousOperation);
previousOperation = "-";
b = "";
} else {
b = b + equation.charAt(i);
}
}
result = performOperation(result, b, previousOperation);
System.out.println("Print Result : " + result);
}
public static String performOperation(String a, String b, String operation) {
int a1 = 0, b1 = 0, res = 0;
if (a != null && !a.equals("")) {
a1 = Integer.parseInt(a);
}
if (b != null && !b.equals("")) {
b1 = Integer.parseInt(b);
}
if (operation.equals("+")) {
res = a1 + b1;
}
if (operation.equals("-")) {
res = a1 - b1;
}
return String.valueOf(res);
}
}
Am using Fck editor to write content. Am storing the text as versions in db. I want to highlight those changes in versions when loading the text in FCK Editor.
How to compare the text....
How to show any text that has been deleted in strike through mode.
Please help me/...
Try google's diff-patch algorithm http://code.google.com/p/google-diff-match-patch/
Take both previous and current version of the text and store it into two parameters. Pass the two parameters to the following function.
function diffString(o, n) {
o = o.replace(/<[^<|>]+?>| /gi, '');
n = n.replace(/<[^<|>]+?>| /gi, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = ["\n"];
} else {
oSpace.push("\n");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = ["\n"];
} else {
nSpace.push("\n");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[i]) + oSpace[i] + "</del></span>";
}
} else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<span style="background-color:#0C0;"><ins>' + escape(out.n[i]) + nSpace[i] + "</ins></span>";
} else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<span style="background-color:#F00;"><del>' + escape(out.o[n]) + oSpace[n] + "</del></span>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
}
this returns an html in which new text is marked green and deleted text as red + striked out.
MS Excel has eaten my head. It is randomly converting numbers into scientific notation format. This causes a problem when I load the file saved in tab delimited format into SQL Server. I know I can provide a format file and do lot of fancy stuff. But let's say I can't.
Is there a macro which loops over all the cells and if the number in a cell is in scientific notation format then it converts it to numeric format?
Say:
Input: spaces signify different cells.
1.00E13 egalitarian
Output after macro:
10000000000000 egalitarian
I am trying this in Excel 2007.
I wrote a simple C# program to resolve this issue. Hope it's of use.
Input:
Input directory where files reside (assuming files are in .txt format).
Output:
Output directory where converted files will be spit out.
Delimiter:
Column delimiter.
The code
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;
namespace ConvertToNumber
{
class Program
{
private static string ToLongString(double input)
{
string str = input.ToString().ToUpper();
// If string representation was collapsed from scientific notation, just return it:
if (!str.Contains("E"))
return str;
var positive = true;
if (input < 0)
{
positive = false;
}
string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
char decSeparator = sep.ToCharArray()[0];
string[] exponentParts = str.Split('E');
string[] decimalParts = exponentParts[0].Split(decSeparator);
// Fix missing decimal point:
if (decimalParts.Length == 1)
decimalParts = new string[] { exponentParts[0], "0" };
int exponentValue = int.Parse(exponentParts[1]);
string newNumber = decimalParts[0].Replace("-","").
Replace("+","") + decimalParts[1];
string result;
if (exponentValue > 0)
{
if(positive)
result =
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
else
result = "-"+
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
}
else // Negative exponent
{
if(positive)
result =
"0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
else
result =
"-0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
result = result.TrimEnd('0');
}
float temp = 0.00F;
if (float.TryParse(result, out temp))
{
return result;
}
throw new Exception();
}
private static string GetZeros(int zeroCount)
{
if (zeroCount < 0)
zeroCount = Math.Abs(zeroCount);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zeroCount; i++) sb.Append("0");
return sb.ToString();
}
static void Main(string[] args)
{
//Get Input Directory.
Console.WriteLine(#"Enter the Input Directory");
var readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the input path properly.");
return;
}
var pathToInputDirectory = readLine.Trim();
//Get Output Directory.
Console.WriteLine(#"Enter the Output Directory");
readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the output path properly.");
return;
}
var pathToOutputDirectory = readLine.Trim();
//Get Delimiter.
Console.WriteLine("Enter the delimiter;");
var columnDelimiter = (char) Console.Read();
//Loop over all files in the directory.
foreach (var inputFileName in Directory.GetFiles(pathToInputDirectory))
{
var outputFileWithouthNumbersInScientificNotation = string.Empty;
Console.WriteLine("Started operation on File : " + inputFileName);
if (File.Exists(inputFileName))
{
// Read the file
using (var file = new StreamReader(inputFileName))
{
string line;
while ((line = file.ReadLine()) != null)
{
String[] columns = line.Split(columnDelimiter);
var duplicateLine = string.Empty;
int lengthOfColumns = columns.Length;
int counter = 1;
foreach (var column in columns)
{
var columnDuplicate = column;
try
{
if (Regex.IsMatch(columnDuplicate.Trim(),
#"^[+-]?[0-9]+(\.[0-9]+)?[E]([+-]?[0-9]+)$",
RegexOptions.IgnoreCase))
{
Console.WriteLine("Regular expression matched for this :" + column);
columnDuplicate = ToLongString(Double.Parse
(column,
System.Globalization.NumberStyles.Float));
Console.WriteLine("Converted this no in scientific notation " +
"" + column + " to this number " +
columnDuplicate);
}
}
catch (Exception)
{
}
duplicateLine = duplicateLine + columnDuplicate;
if (counter != lengthOfColumns)
{
duplicateLine = duplicateLine + columnDelimiter.ToString();
}
counter++;
}
duplicateLine = duplicateLine + Environment.NewLine;
outputFileWithouthNumbersInScientificNotation = outputFileWithouthNumbersInScientificNotation + duplicateLine;
}
file.Close();
}
var outputFilePathWithoutNumbersInScientificNotation
= Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));
//Create the directory if it does not exist.
if (!Directory.Exists(pathToOutputDirectory))
Directory.CreateDirectory(pathToOutputDirectory);
using (var outputFile =
new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
{
outputFile.Write(outputFileWithouthNumbersInScientificNotation);
outputFile.Close();
}
Console.WriteLine("The transformed file is here :" +
outputFilePathWithoutNumbersInScientificNotation);
}
}
}
}
}
This works fairly well in case of huge files which we are unable to open in MS Excel.
Thanks Peter.
I updated your original work to:
1) take in an input file or path
2) only write out a processing statement after every 1000 lines read
3) write the transformed lines to the output file as they are processed so a potentially large string is not kept hanging around
4) added a readkey at the end so that console does not exit automatically while debuggging
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;
namespace ConvertScientificToLong
{
class Program
{
private static string ToLongString(double input)
{
string str = input.ToString().ToUpper();
// If string representation was collapsed from scientific notation, just return it:
if (!str.Contains("E"))
return str;
var positive = true;
if (input < 0)
{
positive = false;
}
string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
char decSeparator = sep.ToCharArray()[0];
string[] exponentParts = str.Split('E');
string[] decimalParts = exponentParts[0].Split(decSeparator);
// Fix missing decimal point:
if (decimalParts.Length == 1)
decimalParts = new string[] { exponentParts[0], "0" };
int exponentValue = int.Parse(exponentParts[1]);
string newNumber = decimalParts[0].Replace("-", "").
Replace("+", "") + decimalParts[1];
string result;
if (exponentValue > 0)
{
if (positive)
result =
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
else
result = "-" +
newNumber +
GetZeros(exponentValue - decimalParts[1].Length);
}
else // Negative exponent
{
if (positive)
result =
"0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
else
result =
"-0" +
decSeparator +
GetZeros(exponentValue + decimalParts[0].Replace("-", "").
Replace("+", "").Length) + newNumber;
result = result.TrimEnd('0');
}
float temp = 0.00F;
if (float.TryParse(result, out temp))
{
return result;
}
throw new Exception();
}
private static string GetZeros(int zeroCount)
{
if (zeroCount < 0)
zeroCount = Math.Abs(zeroCount);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < zeroCount; i++) sb.Append("0");
return sb.ToString();
}
static void Main(string[] args)
{
//Get Input Directory.
Console.WriteLine(#"Enter the Input Directory or File Path");
var readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the input path properly.");
return;
}
var pathToInputDirectory = readLine.Trim();
//Get Output Directory.
Console.WriteLine(#"Enter the Output Directory");
readLine = Console.ReadLine();
if (readLine == null)
{
Console.WriteLine(#"Enter the output path properly.");
return;
}
var pathToOutputDirectory = readLine.Trim();
//Get Delimiter.
Console.WriteLine("Enter the delimiter;");
var columnDelimiter = (char)Console.Read();
string[] inputFiles = null;
if (File.Exists(pathToInputDirectory))
{
inputFiles = new String[]{pathToInputDirectory};
}
else
{
inputFiles = Directory.GetFiles(pathToInputDirectory);
}
//Loop over all files in the directory.
foreach (var inputFileName in inputFiles)
{
var outputFileWithouthNumbersInScientificNotation = string.Empty;
Console.WriteLine("Started operation on File : " + inputFileName);
if (File.Exists(inputFileName))
{
string outputFilePathWithoutNumbersInScientificNotation
= Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));
//Create the directory if it does not exist.
if (!Directory.Exists(pathToOutputDirectory))
Directory.CreateDirectory(pathToOutputDirectory);
using (var outputFile =
new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
{
// Read the file
using (StreamReader file = new StreamReader(inputFileName))
{
string line;
int lineCount = 0;
while ((line = file.ReadLine()) != null)
{
String[] columns = line.Split(columnDelimiter);
var duplicateLine = string.Empty;
int lengthOfColumns = columns.Length;
int counter = 1;
foreach (var column in columns)
{
var columnDuplicate = column;
try
{
if (Regex.IsMatch(columnDuplicate.Trim(),
#"^[+-]?[0-9]+(\.[0-9]+)?[E]([+-]?[0-9]+)$",
RegexOptions.IgnoreCase))
{
//Console.WriteLine("Regular expression matched for this :" + column);
columnDuplicate = ToLongString(Double.Parse
(column,
System.Globalization.NumberStyles.Float));
//Console.WriteLine("Converted this no in scientific notation " +
// "" + column + " to this number " +
// columnDuplicate);
if (lineCount % 1000 == 0)
{
Console.WriteLine(string.Format("processed {0} lines. still going....", lineCount));
}
}
}
catch (Exception)
{
}
duplicateLine = duplicateLine + columnDuplicate;
if (counter != lengthOfColumns)
{
duplicateLine = duplicateLine + columnDelimiter.ToString();
}
counter++;
}
outputFile.WriteLine(duplicateLine);
lineCount++;
}
}
}
Console.WriteLine("The transformed file is here :" +
outputFilePathWithoutNumbersInScientificNotation);
Console.WriteLine(#"Hit any key to exit");
Console.ReadKey();
}
}
}
}
}
An easier way would be to save it as a .csv file. Then, instead of just opening the file - you go to the Data tab and select "from text" so that you can get the dialogue box. This way you can identify that column with the scientific notation as text to wipe out that format. Import the file and then you can reformat it to number or whatever you want.
i am using apache POI , is it possible to read text background and foreground color from ms word paragraph
I got the solution
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
Range range = doc.getRange();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
System.out.println(pr.getEndOffset());
int j=0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
System.out.println("-------------------------------");
System.out.println("Color---"+ run.getColor());
System.out.println("getFontName---"+ run.getFontName());
System.out.println("getFontSize---"+ run.getFontSize());
if( run.getEndOffset()==pr.getEndOffset()){
break;
}
}
}
I found it in :
CharacterRun run = para.getCharacterRun(i)
i should be integer and should be incremented so the code will be as follow :
int c=0;
while (true) {
CharacterRun run = para.getCharacterRun(c++);
int x = run.getPicOffset();
System.out.println("pic offset" + x);
if (run.getEndOffset() == para.getEndOffset()) {
break;
}
}
if (paragraph != null)
{
int numberOfRuns = paragraph.NumCharacterRuns;
for (int runIndex = 0; runIndex < numberOfRuns; runIndex++)
{
CharacterRun run = paragraph.GetCharacterRun(runIndex);
string color = getColor24(run.GetIco24());
}
}
GetColor24 Function to Convert Color in Hex Format for C#
public static String getColor24(int argbValue)
{
if (argbValue == -1)
return "";
int bgrValue = argbValue & 0x00FFFFFF;
int rgbValue = (bgrValue & 0x0000FF) << 16 | (bgrValue & 0x00FF00)
| (bgrValue & 0xFF0000) >> 16;
StringBuilder result = new StringBuilder("#");
String hex = rgbValue.ToString("X");
for (int i = hex.Length; i < 6; i++)
{
result.Append('0');
}
result.Append(hex);
return result.ToString();
}
if you are working on docx(OOXML), you may want to take a look on this:
import java.io.*
import org.apache.poi.xwpf.usermodel.XWPFDocument
fun test(){
try {
val file = File("file.docx")
val fis = FileInputStream(file.absolutePath)
val document = XWPFDocument(fis)
val paragraphs = document.paragraphs
for (para in paragraphs) {
println("-- ("+para.alignment+") " + para.text)
para.runs.forEach { it ->
println(
"text:" + it.text() + " "
+ "(color:" + it.color
+ ",fontFamily:" + it.fontFamily
+ ")"
)
}
}
fis.close()
} catch (e: Exception) {
e.printStackTrace()
}
}