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);
}
}
Related
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;
}
can anybody tell me how to validate Hungarian BBAN account numbres ?
on the internet i have only found that it is 24 numbers length
And in format
bbbs sssk cccc cccc cccc cccx
b = National bank code
s = Branch code
c = Account number
x = National check digit
but how to calculate x = National check digit ?
I have tried to remove last char and modulo rest by 97 but it does not work
(the result is not 1 for valid account numbers)
thanks in advance for any help
I just finished Hungarian account validation function. This is the first version of this function but it's work well.
public string sprawdzWegierskitempAccountNumber(string _accountNumberToCheck, bool _iban) //if iban is true then function result will be always IBAN (even if _accountNumberToCheck will be BBAN)
{
string _accountNumberCorrected = _accountNumberToCheck.Replace(" ", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("-", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("//", "");
_accountNumberCorrected = _accountNumberCorrected.Replace("\", "");
string _accountNumberCorrectedFirst = _accountNumberCorrected;
if (_accountNumberCorrected.Length == 16 || _accountNumberCorrected.Length == 24 || _accountNumberCorrected.Length == 28)
{
if (_accountNumberCorrected.Length == 28) //IBAN Account number
{
_accountNumberCorrected = _accountNumberCorrected.Substring(4, _accountNumberCorrected.Length - 4); //we don't need first four digits (HUxx)
}
string digitToMultiply = "9731";
int checkResult = 0;
//checking first part of account number
for (int i = 0; i <= 6; i++)
{
checkResult = checkResult + int.Parse(_accountNumberCorrected.ToCharArray()[i].ToString()) * int.Parse(digitToMultiply.ToCharArray()[i % 4].ToString());
}
checkResult = checkResult % 10;
checkResult = 10 - checkResult;
if (checkResult == 10)
{
checkResult = 0;
}
if (checkResult.ToString() != _accountNumberCorrected.ToCharArray()[7].ToString())
{
throw new Exception("Wrong account number");
}
else
{
//if first part it's ok then checking second part of account number
checkResult = 0;
for (int i = 8; i <= _accountNumberCorrected.Length-2; i++)
{
checkResult = checkResult + int.Parse(_accountNumberCorrected.ToCharArray()[i].ToString()) * int.Parse(digitToMultiply.ToCharArray()[i % 4].ToString());
}
checkResult = checkResult % 10;
checkResult = 10 - checkResult;
if (checkResult == 10)
{
checkResult = 0;
}
if (checkResult.ToString() != _accountNumberCorrected.ToCharArray()[_accountNumberCorrected.Length-1].ToString())
{
throw new Exception("Wrong account number");
}
}
string tempAccountNumber = _accountNumberCorrected + "173000";
var db = 0; var iban = 0;
var maradek = 0;
string resz = "", ibanstr = "", result = "";
while (true)
{
if (db == 0)
{
resz = tempAccountNumber.Substring(0, 9);
tempAccountNumber = tempAccountNumber.Substring(9, (tempAccountNumber.Length - 9));
}
else
{
resz = maradek.ToString();
resz = resz + tempAccountNumber.Substring(0, (9 - db));
tempAccountNumber = tempAccountNumber.Substring((9 - db), (tempAccountNumber.Length - 9 + db));
}
maradek = int.Parse(resz) % 97;
if (maradek == 0)
db = 0;
else
if (maradek < 10)
db = 1;
else
db = 2;
if ((tempAccountNumber.Length + db) <= 9)
break;
}
if (maradek != 0)
{
resz = maradek.ToString();
resz = resz + tempAccountNumber;
}
else
resz = tempAccountNumber;
maradek = int.Parse(resz) % 97; ;
iban = 98 - maradek;
if (iban < 10)
ibanstr = "0" + iban.ToString();
else ibanstr = iban.ToString();
if (_accountNumberCorrected.Length == 16)
{
_accountNumberCorrected = _accountNumberCorrected + "00000000";
_accountNumberCorrectedFirst = _accountNumberCorrectedFirst + "00000000";
}
if (_iban)
{
result = "HU" + ibanstr + _accountNumberCorrected;
}
else
{
result = _accountNumberCorrectedFirst;
}
return result;
}
else
{
throw new Exception("Wrong length of account number");
}
}
I'm trying to customize a layout of JGraph. I want to create curved edges, but I have a problem. Every time I create a group of vertex on JGraph, and I am firing an event to update this graph, the edge is missing points compared to the previous state. Here is a example:
Can someone help me?
Here is my code:
class CurveGraphView extends mxGraphView {
public CurveGraphView(mxGraph graph) {
super(graph);
}
/* Only override this if you want the label to automatically position itself on the control point */
#Override
public mxPoint getPoint(mxCellState state, mxGeometry geometry) {
double x = state.getCenterX();
double y = state.getCenterY();
if (state.getAbsolutePointCount() == 3) {
mxPoint mid = state.getAbsolutePoint(1);
x = mid.getX();
y = mid.getY();
}
return new mxPoint(x, y);
}
// /* Makes sure that the full path of the curve is included in the bounding box */
#Override
public mxRectangle updateBoundingBox(mxCellState state) {
List<mxPoint> points = state.getAbsolutePoints();
mxRectangle bounds = super.updateBoundingBox(state);
Object style = state.getStyle().get("edgeStyle");
if (CurvedEdgeStyle.KEY.equals(style) && points != null && points.size() == 3) {
Rectangle pathBounds = CurvedShape.createPath(state.getAbsolutePoints()).getBounds();
Rectangle union = bounds.getRectangle().union(pathBounds);
bounds = new mxRectangle(union);
state.setBoundingBox(bounds);
}
return bounds;
}
}
class CurvedEdgeStyle implements mxEdgeStyle.mxEdgeStyleFunction {
public static final String KEY = "curvedEdgeStyle";
#Override
public void apply(mxCellState state, mxCellState source, mxCellState target, List<mxPoint> points, List<mxPoint> result) {
mxPoint pt = (points != null && points.size() > 0) ? points.get(0) : null;
if (source != null && target != null) {
double x = 0;
double y = 0;
if (pt != null) {
result.add(pt);
} else {
x = (target.getCenterX() + source.getCenterX()) / 2;
y = (target.getCenterY() + source.getCenterY()) / 2;
mxPoint point = new mxPoint(x, y);
result.add(point);
}
}
}
}
class CurvedShape extends mxConnectorShape {
public static final String KEY = "curvedEdge";
private GeneralPath path;
#Override
public void paintShape(mxGraphics2DCanvas canvas, mxCellState state) {
List<mxPoint> abs = state.getAbsolutePoints();
int n = state.getAbsolutePointCount();
mxCell aux = (mxCell)state.getCell();
if (n < 3) {
super.paintShape(canvas, state);
} else if (configureGraphics(canvas, state, false)) {
Graphics2D g = canvas.getGraphics();
path = createPath(abs);
g.draw(path);
paintMarker(canvas, state, false);
paintMarker(canvas, state, true);
}
}
/* Code borrowed from here: http://www.codeproject.com/Articles/31859/Draw-a-Smooth-Curve-through-a-Set-of-2D-Points-wit */
public static GeneralPath createPath(List<mxPoint> abs) {
mxPoint[] knots = abs.toArray(new mxPoint[abs.size()]);
int n = knots.length - 1;
mxPoint[] firstControlPoints = new mxPoint[n];
mxPoint[] secondControlPoints = new mxPoint[n]; // Calculate first Bezier control points // Right hand side vector
double[] rhs = new double[n]; // Set right hand side X values
for (int i = 1; i < n - 1; ++i) {
rhs[i] = 4 * knots[i].getX() + 2 * knots[i + 1].getX();
}
rhs[0] = knots[0].getX() + 2 * knots[1].getX();
rhs[n - 1] = (8 * knots[n - 1].getX() + knots[n].getX()) / 2.0; // Get first control points X-values
double[] x = getFirstControlPoints(rhs); // Set right hand side Y values
for (int i = 1; i < n - 1; ++i) {
rhs[i] = 4 * knots[i].getY() + 2 * knots[i + 1].getY();
}
rhs[0] = knots[0].getY() + 2 * knots[1].getY();
rhs[n - 1] = (8 * knots[n - 1].getY() + knots[n].getY()) / 2.0; // Get first control points Y-values
double[] y = getFirstControlPoints(rhs); // Fill output arrays.
for (int i = 0; i < n; ++i) { // First control point
firstControlPoints[i] = new mxPoint(x[i], y[i]); // Second control point
if (i < n - 1) {
secondControlPoints[i] = new mxPoint(2 * knots[i + 1].getX() - x[i + 1], 2 * knots[i + 1].getY() - y[i + 1]);
} else {
secondControlPoints[i] = new mxPoint((knots[n].getX() + x[n - 1]) / 2, (knots[n].getY() + y[n - 1]) / 2);
}
}
GeneralPath path = new GeneralPath();
path.moveTo(knots[0].getX(), knots[0].getY());
for (int i = 1; i < n + 1; i++) {
path.curveTo(firstControlPoints[i - 1].getX(), firstControlPoints[i - 1].getY(), secondControlPoints[i - 1].getX(), secondControlPoints[i - 1].getY(), knots[i].getX(), knots[i].getY());
}
return path;
}/// <summary>/// Solves a tridiagonal system for one of coordinates (x or y)/// of first Bezier control points./// </summary>/// <param name="rhs">Right hand side vector.</param>/// <returns>Solution vector.</returns>
private static double[] getFirstControlPoints(double[] rhs) {
int n = rhs.length;
double[] x = new double[n]; // Solution vector.
double[] tmp = new double[n]; // Temp workspace.
double b = 2.0;
x[0] = rhs[0] / b;
for (int i = 1; i < n; i++) // Decomposition and forward substitution.
{
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (int i = 1; i < n; i++) {
x[n - i - 1] -= tmp[n - i] * x[n - i]; // Backsubstitution.
}
return x;
}
#Override
protected mxLine getMarkerVector(List<mxPoint> points, boolean source, double markerSize) {
if (path == null || points.size() < 3) {
return super.getMarkerVector(points, source, markerSize);
}
double coords[] = new double[6];
double x0 = 0;
double y0 = 0;
double x1 = 0;
double y1 = 0;
PathIterator p = path.getPathIterator(null, 2.0);
if (source) {
p.currentSegment(coords);
x1 = coords[0];
y1 = coords[1];
p.next();
p.currentSegment(coords);
x0 = coords[0];
y0 = coords[1];
} else {
while (!p.isDone()) {
p.currentSegment(coords);
x0 = x1;
y0 = y1;
x1 = coords[0];
y1 = coords[1];
p.next();
}
}
return new mxLine(x0, y0, new mxPoint(x1, y1));
}
}
extends mxGraph and Override the constructor adding:
mxGraphics2DCanvas.putShape(CurvedShape.KEY, new CurvedShape());
mxStyleRegistry.putValue(CurvedEdgeStyle.KEY, new CurvedEdgeStyle());
getStylesheet().getDefaultEdgeStyle().put(mxConstants.STYLE_SHAPE, CurvedShape.KEY);
getStylesheet().getDefaultEdgeStyle().put(mxConstants.STYLE_EDGE, CurvedEdgeStyle.KEY);
and Override createGraphView() returning CurveGraphView.
Have told me it has to do something with absolute points.
The String(byte[] bytes) constructor and String.getBytes() method are not implemented by GWT JRE emulation String class.
Does anybody know of an implementation? I do not want to use char[], But it seems like there is no other solution.
If you create large arrays in Chrome, you might run into a Uncaught RangeError: Maximum call stack size exceeded exception. The code from LINEMAN78 can be modified to use a StringBuilder, which avoids this issue.
public static String getString(byte[] bytes, int bytesPerChar)
{
if (bytes == null) throw new IllegalArgumentException("bytes cannot be null");
if (bytesPerChar < 1) throw new IllegalArgumentException("bytesPerChar must be greater than 1");
final int length = bytes.length / bytesPerChar;
final StringBuilder retValue = new StringBuilder();
for (int i = 0; i < length; i++)
{
char thisChar = 0;
for (int j = 0; j < bytesPerChar; j++)
{
int shift = (bytesPerChar - 1 - j) * 8;
thisChar |= (0x000000FF << shift) & (((int) bytes[i * bytesPerChar + j]) << shift);
}
retValue.append(thisChar);
}
return retValue.toString();
}
The following code should work, just specify the number of bytes per character.
public class GwtPlayground implements EntryPoint
{
static final Logger logger = Logger.getLogger("");
#Override
public void onModuleLoad()
{
VerticalPanel loggerArea = new VerticalPanel();
logger.addHandler(new HasWidgetsLogHandler(loggerArea));
RootPanel.get().add(loggerArea);
String original = new String("A" + "\uffea" + "\u00f1" + "\u00fc" + "C");
logger.info("original = " + original);
byte[] utfBytes = getBytes(original, 2);
String roundTrip = getString(utfBytes, 2);
logger.info("roundTrip = " + roundTrip);
}
public static byte[] getBytes(String string, int bytesPerChar)
{
char[] chars = string.toCharArray();
byte[] toReturn = new byte[chars.length * bytesPerChar];
for (int i = 0; i < chars.length; i++)
{
for (int j = 0; j < bytesPerChar; j++)
toReturn[i * bytesPerChar + j] = (byte) (chars[i] >>> (8 * (bytesPerChar - 1 - j)));
}
return toReturn;
}
public static String getString(byte[] bytes, int bytesPerChar)
{
char[] chars = new char[bytes.length / bytesPerChar];
for (int i = 0; i < chars.length; i++)
{
for (int j = 0; j < bytesPerChar; j++)
{
int shift = (bytesPerChar - 1 - j) * 8;
chars[i] |= (0x000000FF << shift) & (((int) bytes[i * bytesPerChar + j]) << shift);
}
}
return new String(chars);
}
}
As #Per Wiklander pointed out, this doesn't truely support UTF-8. Here is a true UTF-8 decoder ported from C here
private static class UTF8Decoder
{
final byte[] the_input;
int the_index, the_length;
protected UTF8Decoder( byte[] bytes )
{
super();
this.the_input = bytes;
this.the_index = 0;
this.the_length = bytes.length;
}
/*
Get the next byte. It returns UTF8_END if there are no more bytes.
*/
int get()
{
int c;
c = the_input[the_index] & 0xFF;
the_index += 1;
return c;
}
/*
Get the 6-bit payload of the next continuation byte.
Return UTF8_ERROR if it is not a contination byte.
*/
int cont()
{
int c = get();
if( (c & 0xC0) == 0x80 )
return (c & 0x3F);
else
throw new IllegalArgumentException( "Failed to pass strict UTF-8" );
}
CharSequence getStringUTF8()
{
StringBuilder sb = new StringBuilder( the_input.length ); // allocate a maximum size
while( the_index < the_length )
{
int c; /* the first byte of the character */
int r; /* the result */
c = get();
/*
Zero continuation (0 to 127)
*/
if( (c & 0x80) == 0 )
{
sb.append( (char) c );
}
/*
One continuation (128 to 2047)
*/
else if( (c & 0xE0) == 0xC0 )
{
int c1 = cont();
if( c1 >= 0 )
{
r = ((c & 0x1F) << 6) | c1;
if( r >= 128 )
sb.append( (char) r );
else
throw new IllegalArgumentException();
}
}
/*
Two continuation (2048 to 55295 and 57344 to 65535)
*/
else if( (c & 0xF0) == 0xE0 )
{
int c1 = cont();
int c2 = cont();
if( (c1 | c2) >= 0 )
{
r = ((c & 0x0F) << 12) | (c1 << 6) | c2;
if( r >= 2048 && (r < 55296 || r > 57343) )
sb.append( (char) r );
else
throw new IllegalArgumentException();
}
}
/*
Three continuation (65536 to 1114111)
*/
else if( (c & 0xF8) == 0xF0 )
{
int c1 = cont();
int c2 = cont();
int c3 = cont();
if( (c1 | c2 | c3) >= 0 )
sb.append( (char) ((((c & 0x0F) << 18) | (c1 << 12) | (c2 << 6) | c3) + 65536) ); // TODO this might not work as it is being cast to a char
}
else
throw new IllegalArgumentException( "Failed strict UTF8 parsing" );
}
return sb;
}
}
Good question. I didn't realize it before.
as far as I know there is only 2 main method that convert byte array to String
You mentioned it
The fantastic way with java.io package that you can't use it on client-side
Here is mine implementation. I think it may be helpful to you
public static String convertByteArrayToString(byte[] byteArray) {
String s = "";
for (int i = 0; i < byteArray.length; i++) {
s += (char) (byteArray[i]);
}
return s;
}
You can test it :
byte[] byteArray = new byte[] { 87, 79, 87, 46, 46, 46 };
System.out.println(convertByteArrayToString(byteArray));
System.out.println(new String(byteArray));
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()
}
}