Search Results

Search found 36065 results on 1443 pages for 'string manipulation'.

Page 15/1443 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • java: converting part of a ByteBuffer to a string

    - by Jason S
    I have a ByteBuffer containing bytes that were derived by String.getBytes(charsetName), where "containing" means that the string comprises the entire sequence of bytes between the ByteBuffer's position() and limit(). What's the best way for me to get the string back? (assuming I know the encoding charset) Is there anything better than the following (which seems a little clunky) byte[] ba = new byte[bbuf.remaining()]; bbuf.get(ba); try { String s = new String(ba, charsetName); } catch (UnsupportedEncodingException e) { /* take appropriate action */ }

    Read the article

  • Using fgets to read strings from file in C

    - by Ivan
    I am trying to read strings from a file that has each string on a new line but I think it reads a newline character once instead of a string and I don't know why. If I'm going about reading strings the wrong way please correct me. i=0; F1 = fopen("alg.txt", "r"); F2 = fopen("tul.txt", "w"); if(!feof(F1)) { do{ //start scanning file fgets(inimene[i].Enimi, 20, F1); fgets(inimene[i].Pnimi, 20, F1); fgets(inimene[i].Kood, 12, F1); printf("i=%d\nEnimi=%s\nPnimi=%s\nKaad=%s",i,inimene[i].Enimi,inimene[i].Pnimi,inimene[i].Kood); i++;} while(!feof(F1));}; /*finish getting structs*/ The printf is there to let me see what was read into what and here is the result i=0 Enimi=peter Pnimi=pupkin Kood=223456iatb i=1 Enimi= Pnimi=masha Kaad=gubkina i=2 Enimi=234567iasb Pnimi=sasha Kood=dudkina As you can see after the first struct is read there is a blank(a newline?) onct and then everything is shifted. I suppose I could read a dummy string to absorb that extra blank and then nothing would be shifted, but that doesn't help me understand the problem and avoid in the future.

    Read the article

  • PHP - Find a string in file then show it's line number

    - by xZero
    I have an application which needs to open the file, then find string in it, and print a line number where is string found. For example, file example.txt contains few hashes: APLF2J51 1a79a4d60de6718e8e5b326e338ae533 EEQJE2YX 66b375b08fc869632935c9e6a9c7f8da O87IGF8R c458fb5edb84c54f4dc42804622aa0c5 APLF2J51 B7TSW1ZE 1e9eea56686511e9052e6578b56ae018 EEQJE2YX affb23b07576b88d1e9fea50719fb3b7 So, I want to PHP search for "1e9eea56686511e9052e6578b56ae018" and print out its line number, in this case 4. Please note that there are will not be multiple hashes in file. I found a few codes over Internet, but none seem to work. I tried this one: <?PHP $string = "1e9eea56686511e9052e6578b56ae018"; $data = file_get_contents("example.txt"); $data = explode("\n", $data); for ($line = 0; $line < count($data); $line++) { if (strpos($data[$line], $string) >= 0) { die("String $string found at line number: $line"); } } ?> It just says that string is found at line 0.... Which is not correct.... Final application is much more complex than that... After it founds line number, it should replace string which something else, and save changes to file, then goes further processing.... Thanks in advance :)

    Read the article

  • Reverse String Error?

    - by R41nB0w M47r1z
    I am creating this revese string App but i get a error if i include a space in the string ! #include <iostream> #include <string> using namespace std; int main() { int inputa; cout<<"%%%%%%%%%%%%%%%%%%String Reversing App%%%%%%%%%%%%%%%%%%%%%%%%"<<endl<<endl; cout<<"\nEnter 1 to continue and 0 to exit"<<endl<<endl; cin>>inputa; if(inputa!=0) { do { string a,c=""; cout<<"\nEnter the string you want to Reverse : "; cin>>a; for(int x=a.length()-1; x>=0; x--) { c=c+a.substr(x,1); } cout<<"\nThe Reverse String is : "<<c<<endl; cout<<"\nEnter 1 to continue and 0 to exit"<<endl<<endl; cin>>inputa; } while(inputa!=0); } //not my home work } If I type the following string like "abc def" there i get an error . But otherwise it works perfectly ! Is there some mistake with the codes ! I am new to CPP so it would be helpful if you could help me !

    Read the article

  • Java :Interface for this code

    - by ibrahim
    Please i neeed help to make interface for this code: package com.ejada.alinma.edh.xsdtransform; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /*import org.apache.log4j.Logger;*/ import org.apache.log4j.PropertyConfigurator; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; /** * An XSD Transformer that replaces the "name" attribute's value in T24 XSDs * with the "shortname" attribute's value * * @author ahusseiny * */ public class XSDTransformer { /** * constants representing the XSD tags and attributes' names used in the parse process */ public static final String TAG_SCHEMA = "xsd:schema"; public static final String TAG_TEXT = "#text"; public static final String TAG_COMPLEX_TYPE = "xsd:complexType"; public static final String TAG_SIMPLE_TYPE = "xsd:simpleType"; public static final String TAG_SEQUENCE = "xsd:sequence"; public static final String TAG_ATTRIBUTE = "xsd:attribute"; public static final String TAG_ELEMENT = "xsd:element"; public static final String TAG_ANNOTATION = "xsd:annotation"; public static final String TAG_APP_INFO = "xsd:appinfo"; public static final String TAG_HAS_PROPERTY = "xsd:hasProperty"; public static final String TAG_RESTRICTION = "xsd:restriction"; public static final String TAG_MAX_LENGTH = "xsd:maxLength"; public static final String ATTR_NAME = "name"; public static final String ATTR_VALUE = "value"; public static final String ATTR_TYPE = "type"; public static final String ATTR_MIXED = "mixed"; public static final String ATTR_USE = "use"; public static final String ATTR_REF = "ref"; public static final String ATTR_MAX_OCCURS = "maxOccurs"; /** * constants representing specific XSD attributes' values used in the parse process */ public static final String FIELD_TAG = "fieldtag"; public static final String FIELD_NUMBER = "fieldnumber"; public static final String FIELD_DATA_TYPE = "fielddatatype"; public static final String FIELD_FMT = "fieldfmt"; public static final String FIELD_LEN = "fieldlen"; public static final String FIELD_INPUT_LEN = "fieldinputlen"; public static final String FIELD_GROUP_NUMBER = "fieldgroupnumber"; public static final String FIELD_MV_GROUP_NUMBER = "fieldmvgroupnumber"; public static final String FIELD_SHORT_NAME = "fieldshortname"; public static final String FIELD_NAME = "fieldname"; public static final String FIELD_COLUMN_NAME = "fieldcolumnname"; public static final String FIELD_GROUP_NAME = "fieldgroupname"; public static final String FIELD_MV_GROUP_NAME = "fieldmvgroupname"; public static final String FIELD_JUSTIFICATION = "fieldjustification"; public static final String FIELD_TYPE = "fieldtype"; public static final String FIELD_SINGLE_OR_MULTI = "singleormulti"; public static final String DELIMITER_COLUMN_TYPE = "#"; public static final String COLUMN_FK_ROW = "FK_ROW"; public static final String COLUMN_XPK_ROW = "XPK_ROW"; public static final int SQL_VIEW_MULTI = 1; public static final int SQL_VIEW_SINGLE = 2; public static final String DATA_TYPE_XSD_NUMERIC = "numeric"; public static final String DATA_TYPE_XSD_DECIMAL = "decimal"; public static final String DATA_TYPE_XSD_STRING = "string"; public static final String DATA_TYPE_XSD_DATE = "date"; /** * application configuration properties */ public static final String PROP_LOG4J_CONFIG_FILE = "log4j_config"; public static final String PROP_MAIN_VIEW_NAME_SINGLE = "view_name_single"; public static final String PROP_MAIN_VIEW_NAME_MULTI = "view_name_multi"; public static final String PROP_MAIN_TABLE_NAME = "main_edh_table_name"; public static final String PROP_SUB_TABLE_PREFIX = "sub_table_prefix"; public static final String PROP_SOURCE_XSD_FULLNAME = "source_xsd_fullname"; public static final String PROP_RESULTS_PATH = "results_path"; public static final String PROP_NEW_XSD_FILENAME = "new_xsd_filename"; public static final String PROP_CSV_FILENAME = "csv_filename"; /** * static holders for application-level utilities */ private static Properties appProps; private static Logger appLogger; /** * */ private StringBuffer sqlViewColumnsSingle = null; private StringBuffer sqlViewSelectSingle = null; private StringBuffer columnsCSV = null; private ArrayList<String> singleValueTableColumns = null; private HashMap<String, String> multiValueTablesSQL = null; private HashMap<Object, HashMap<String, Object>> groupAttrs = null; public XSDTransformer(String appConfigPropsPath) { if (appProps == null) { appProps = new Properties(); } try { init(appConfigPropsPath); } catch (Exception e) { appLogger.error(e.getMessage()); } } /** * initialization */ private void init(String appConfigPropsPath) throws Exception { // init the properties object FileReader in = new FileReader(appConfigPropsPath); appProps.load(in); // init the logger if ((appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE) != null) && (!appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE).equals(""))) { PropertyConfigurator.configure(appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE)); if (appLogger == null) { appLogger = Logger.getLogger(XSDTransformer.class.getName()); } appLogger.info("Application initialization successful."); } sqlViewColumnsSingle = new StringBuffer(); sqlViewSelectSingle = new StringBuffer(); columnsCSV = new StringBuffer(XSDTransformer.FIELD_TAG + "," + XSDTransformer.FIELD_NUMBER + "," + XSDTransformer.FIELD_DATA_TYPE + "," + XSDTransformer.FIELD_FMT + "," + XSDTransformer.FIELD_LEN + "," + XSDTransformer.FIELD_INPUT_LEN + "," + XSDTransformer.FIELD_GROUP_NUMBER + "," + XSDTransformer.FIELD_MV_GROUP_NUMBER + "," + XSDTransformer.FIELD_SHORT_NAME + "," + XSDTransformer.FIELD_NAME + "," + XSDTransformer.FIELD_COLUMN_NAME + "," + XSDTransformer.FIELD_GROUP_NAME + "," + XSDTransformer.FIELD_MV_GROUP_NAME + "," + XSDTransformer.FIELD_JUSTIFICATION + "," + XSDTransformer.FIELD_TYPE + "," + XSDTransformer.FIELD_SINGLE_OR_MULTI + System.getProperty("line.separator")); singleValueTableColumns = new ArrayList<String>(); singleValueTableColumns.add(XSDTransformer.COLUMN_XPK_ROW + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_NUMERIC); multiValueTablesSQL = new HashMap<String, String>(); groupAttrs = new HashMap<Object, HashMap<String, Object>>(); } /** * initialize the <code>DocumentBuilder</code> and read the XSD file * * @param docPath * @return the <code>Document</code> object representing the read XSD file */ private Document retrieveDoc(String docPath) { Document xsdDoc = null; File file = new File(docPath); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xsdDoc = builder.parse(file); } catch (Exception e) { appLogger.error(e.getMessage()); } return xsdDoc; } /** * perform the iteration/modification on the document * iterate to the level which contains all the elements (Single-Value, and Groups) and start processing each * * @param xsdDoc * @return */ private Document transformDoc(Document xsdDoc) { ArrayList<Object> newElementsList = new ArrayList<Object>(); HashMap<String, Object> docAttrMap = new HashMap<String, Object>(); Element sequenceElement = null; Element schemaElement = null; // get document's root element NodeList nodes = xsdDoc.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (XSDTransformer.TAG_SCHEMA.equals(nodes.item(i).getNodeName())) { schemaElement = (Element) nodes.item(i); break; } } // process the document (change single-value elements, collect list of new elements to be added) for (int i1 = 0; i1 < schemaElement.getChildNodes().getLength(); i1++) { Node childLevel1 = (Node) schemaElement.getChildNodes().item(i1); // <ComplexType> element if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // first, get the main attributes and put it in the csv file for (int i6 = 0; i6 < childLevel1.getChildNodes().getLength(); i6++) { Node child6 = childLevel1.getChildNodes().item(i6); if (XSDTransformer.TAG_ATTRIBUTE.equals(child6.getNodeName())) { if (child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { String attrName = child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); if (((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { Node simpleTypeElement = ((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE) .item(0); if (((Element) simpleTypeElement).getElementsByTagName(XSDTransformer.TAG_RESTRICTION).getLength() != 0) { Node restrictionElement = ((Element) simpleTypeElement).getElementsByTagName( XSDTransformer.TAG_RESTRICTION).item(0); if (((Element) restrictionElement).getElementsByTagName(XSDTransformer.TAG_MAX_LENGTH).getLength() != 0) { Node maxLengthElement = ((Element) restrictionElement).getElementsByTagName( XSDTransformer.TAG_MAX_LENGTH).item(0); HashMap<String, String> elementProperties = new HashMap<String, String>(); elementProperties.put(XSDTransformer.FIELD_TAG, attrName); elementProperties.put(XSDTransformer.FIELD_NUMBER, "0"); elementProperties.put(XSDTransformer.FIELD_DATA_TYPE, XSDTransformer.DATA_TYPE_XSD_STRING); elementProperties.put(XSDTransformer.FIELD_FMT, ""); elementProperties.put(XSDTransformer.FIELD_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SHORT_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_COLUMN_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); elementProperties.put(XSDTransformer.FIELD_LEN, maxLengthElement.getAttributes().getNamedItem( XSDTransformer.ATTR_VALUE).getNodeValue()); elementProperties.put(XSDTransformer.FIELD_INPUT_LEN, maxLengthElement.getAttributes() .getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); constructElementRow(elementProperties); // add the attribute as a column in the single-value table singleValueTableColumns.add(attrName + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_STRING + XSDTransformer.DELIMITER_COLUMN_TYPE + maxLengthElement.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); // add the attribute as a column in the single-values view sqlViewColumnsSingle.append(System.getProperty("line.separator") + attrName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + attrName + ", "); appLogger.debug("added attribute: " + attrName); } } } } } } // now, loop on the elements and process them for (int i2 = 0; i2 < childLevel1.getChildNodes().getLength(); i2++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(i2); // <Sequence> element if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { sequenceElement = (Element) childLevel2; for (int i3 = 0; i3 < childLevel2.getChildNodes().getLength(); i3++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(i3); // <Element> element if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { processGroup(childLevel3, true, null, docAttrMap, xsdDoc, newElementsList); // insert a new comment node with the contents of the group tag sequenceElement.insertBefore(xsdDoc.createComment(serialize(childLevel3)), childLevel3); // remove the group tag sequenceElement.removeChild(childLevel3); } else { processElement(childLevel3); } } } } } } } // add new elements // this step should be after finishing processing the whole document. when you add new elements to the document // while you are working on it, those new elements will be included in the processing. We don't need that! for (int i = 0; i < newElementsList.size(); i++) { sequenceElement.appendChild((Element) newElementsList.get(i)); } // write the new required attributes to the schema element Iterator<String> attrIter = docAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) docAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("appending attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_NAME, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_TYPE, attr.getAttribute(XSDTransformer.ATTR_TYPE)); schemaElement.appendChild(newAttrElement); } return xsdDoc; } /** * check if the <code>element</code> sent is single-value element or group * element. the comparison depends on the children of the element. if found one of type * <code>ComplexType</code> then it's a group element, and if of type * <code>SimpleType</code> then it's a single-value element * * @param element * @return <code>true</code> if the element is a group element, * <code>false</code> otherwise */ private boolean isGroup(Node element) { for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node child = (Node) element.getChildNodes().item(i); if (child.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // found a ComplexType child (Group element) return true; } else if (child.getNodeName().equals(XSDTransformer.TAG_SIMPLE_TYPE)) { // found a SimpleType child (Single-Value element) return false; } } return false; /* String attrName = null; if (element.getAttributes() != null) { Node attribute = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); } } if (attrName.startsWith("g")) { // group element return true; } else { // single element return false; } */ } /** * process a group element. recursively, process groups till no more group elements are found * * @param element * @param isFirstLevelGroup * @param attrMap * @param docAttrMap * @param xsdDoc * @param newElementsList */ private void processGroup(Node element, boolean isFirstLevelGroup, Node parentGroup, HashMap<String, Object> docAttrMap, Document xsdDoc, ArrayList<Object> newElementsList) { String elementName = null; HashMap<String, Object> groupAttrMap = new HashMap<String, Object>(); HashMap<String, Object> parentGroupAttrMap = new HashMap<String, Object>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing group [" + elementName + "]..."); // get the attributes if a non-first-level-group // attributes are: groups's own attributes + parent group's attributes if (!isFirstLevelGroup) { // get the current element (group) attributes for (int i1 = 0; i1 < element.getChildNodes().getLength(); i1++) { if (XSDTransformer.TAG_COMPLEX_TYPE.equals(element.getChildNodes().item(i1).getNodeName())) { Node complexTypeNode = element.getChildNodes().item(i1); for (int i2 = 0; i2 < complexTypeNode.getChildNodes().getLength(); i2++) { if (XSDTransformer.TAG_ATTRIBUTE.equals(complexTypeNode.getChildNodes().item(i2).getNodeName())) { appLogger.debug("add group attr: " + ((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME)); groupAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); docAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); } } } } // now, get the parent's attributes parentGroupAttrMap = groupAttrs.get(parentGroup); if (parentGroupAttrMap != null) { Iterator<String> iter = parentGroupAttrMap.keySet().iterator(); while (iter.hasNext()) { String attrName = iter.next(); groupAttrMap.put(attrName, parentGroupAttrMap.get(attrName)); } } // put the attributes in the attributes map groupAttrs.put(element, groupAttrMap); } for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { // another group element.. // unfortunately, a recursion is // needed here!!! :-( processGroup(childLevel3, false, element, docAttrMap, xsdDoc, newElementsList); } else { // reached a single-value element.. copy it under the // main sequence and apply the name-shorname // replacement processGroupElement(childLevel3, element, isFirstLevelGroup, xsdDoc, newElementsList); } } } } } } } appLogger.debug("finished processing group [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. replace the <code>name</code> attribute with the <code>shortname</code>. * * @param element */ private void processElement(Node element) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_INPUT_LEN)) { fieldInputLength = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } } } } } } } } } if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).setNodeValue(fieldShortName); } sqlViewColumnsSingle.append(System.getProperty("line.separator") + fieldColumnName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + fieldShortName + ", "); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); constructElementRow(elementProperties); singleValueTableColumns.add(fieldShortName + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldDataType + fieldFormat + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldInputLength); appLogger.debug("finished processing element [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. copy the element under the main sequence * 2. replace the <code>name</code> attribute with the <code>shortname</code>. * 3. add the attributes of the parent groups (if non-first-level-group) * * @param element */ private void processGroupElement(Node element, Node parentGroup, boolean isFirstLevelGroup, Document xsdDoc, ArrayList<Object> newElementsList) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; Element newElement = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); ArrayList<String> tableColumns = new ArrayList<String>(); HashMap<String, Object> groupAttrMap = null; if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); // 1. copy the element newElement = (Element) element.cloneNode(true); newElement.setAttribute(XSDTransformer.ATTR_MAX_OCCURS, "unbounded"); // 2. if non-first-level-group, replace the element's SimpleType tag with a ComplexType tag if (!isFirstLevelGroup) { if (((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { // there should be only one tag of SimpleType Node simpleTypeNode = ((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).item(0); // create the new ComplexType element Element complexTypeNode = xsdDoc.createElement(XSDTransformer.TAG_COMPLEX_TYPE); complexTypeNode.setAttribute(XSDTransformer.ATTR_MIXED, "true"); // get the list of attributes for the parent group groupAttrMap = groupAttrs.get(parentGroup); Iterator<String> attrIter = groupAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) groupAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("adding attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_REF, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_USE, "optional"); complexTypeNode.appendChild(newAttrElement); } // replace the old SimpleType node with the new ComplexType node newElement.replaceChild(complexTypeNode, simpleTypeNode); } } // 3. replace the name with the shortname in the new element for (int i = 0; i < newElement.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) newElement.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE)

    Read the article

  • Cleanest way to build an SQL string in Java

    - by Vidar
    I want to build an SQL string to do database manipulation (updates, deletes, inserts, selects, that sort of thing) - instead of the awful string concat method using millions of "+"'s and quotes which is unreadable at best - there must be a better way. I did think of using MessageFormat - but its supposed to be used for user messages, although I think it would do a reasonable job - but I guess there should be something more aligned to SQL type operations in the java sql libraries. Would Groovy be any good? Any help much appreciated.

    Read the article

  • C++ exam question on string class implementation

    - by Carlucho
    I just took an exam where i was asked the following: Write the function body of each of the methods GenStrLen, InsertChar and StrReverse for the given code bellow. You must take into consideration the following; How strings are constructed in C++ The string must not overflow Insertion of character increases its length by 1 An empty string is indicated by StrLen = 0 class Strings { private: char str[80]; int StrLen; public: // Constructor Strings() { StrLen=0; }; // A function for returning the length of the string 'str' int GetStrLen(void) { }; // A function to inser a character 'ch' at the end of the string 'str' void InsertChar(char ch) { }; // A function to reverse the content of the string 'str' void StrReverse(void) { }; }; The answer I gave was something like this (see bellow). My one of problem is that used many extra variables and that makes me believe am not doing it the best possible way, and the other thing is that is not working.... class Strings { private: char str[80]; int StrLen; int index; // *** Had to add this *** public: Strings(){ StrLen=0; } int GetStrLen(void){ for (int i=0 ; str[i]!='\0' ; i++) index++; return index; // *** Here am getting a weird value, something like 1829584505306 *** } void InsertChar(char ch){ str[index] = ch; // *** Not sure if this is correct cuz I was not given int index *** } void StrRevrse(void){ GetStrLen(); char revStr[index+1]; for (int i=0 ; str[i]!='\0' ; i++){ for (int r=index ; r>0 ; r--) revStr[r] = str[i]; } } }; I would appreciate if anyone could explain me toughly what is the best way to have answered the question and why. Also how come my professor closes each class function like " }; " i thought that was only used for ending classes and constructors only. Thanks a lot for your help.

    Read the article

  • Partial string search in boost::multi_index_container

    - by user361699
    I have a struct to store info about persons and multi_index_contaider to store such objects struct person { std::string m_first_name; std::string m_last_name; std::string m_third_name; std::string m_address; std::string m_phone; person(); person(std::string f, std::string l, std::string t = "", std::string a = DEFAULT_ADDRESS, std::string p = DEFAULT_PHONE) : m_first_name(f), m_last_name(l), m_third_name(t), m_address(a), m_phone(p) {} }; typedef multi_index_container , ordered_non_unique, member, member persons_set; operator< and operator<< implementation for person bool operator<(const person &lhs, const person &rhs) { if(lhs.m_last_name == rhs.m_last_name) { if(lhs.m_first_name == rhs.m_first_name) return (lhs.m_third_name < rhs.m_third_name); return (lhs.m_first_name < rhs.m_first_name); } return (lhs.m_last_name < rhs.m_last_name); } std::ostream& operator<<(std::ostream &s, const person &rhs) { s << "Person's last name: " << rhs.m_last_name << std::endl; s << "Person's name: " << rhs.m_first_name << std::endl; if (!rhs.m_third_name.empty()) s << "Person's third name: " << rhs.m_third_name << std::endl; s << "Phone: " << rhs.m_phone << std::endl; s << "Address: " << rhs.m_address << std::endl; return s; } Add several persons into container: person ("Alex", "Johnson", "Somename"); person ("Alex", "Goodspeed"); person ("Petr", "Parker"); person ("Petr", "Goodspeed"); Now I want to find person by lastname (the first member of the second index in multi_index_container) persons_set::nth_index<1::type &names_index = my_set.get<1(); std::pair::type::const_iterator, persons_set::nth_index<1::type::const_iterator n_it = names_index.equal_range("Goodspeed"); std::copy(n_it.first ,n_it.second, std::ostream_iterator(std::cout)); It works great. Both 'Goodspeed' persons are found. Now lets try to find person by a part of a last name: std::pair::type::const_iterator, persons_set::nth_index<1::type::const_iterator n_it = names_index.equal_range("Good"); std::copy(n_it.first ,n_it.second, std::ostream_iterator(std::cout)); This returns nothing, but partial string search works as a charm in std::set. So I can't realize what's the problem. I only wraped strings by a struct. May be operator< implementation? Thanks in advance for any help.

    Read the article

  • Segfault on copy constructor for string

    - by user2756569
    I'm getting a segfault on a line where I'm creating a c++ string with the copy constructor. I've looked at some of the similar issues, but they're all due to passing in a bad c++ string object. I'm just passing in a raw string, so I'm not sure what my issue is. I'll paste the relevant snippets of code (it's taken from several different files, so it might look a bit jumbled). The segfault occurs in the 4th line of the default constructor for the Species class. Species::Species(string _type) { program_length = 0; cout << _type << " 1\n"; cout << type << " 2\n"; type = string(_type); } Grid::Grid(int _width, int _height) { *wall = Species("wall"); *empty = Species("empty"); turn_number = 0; width = _width; height = _height; for(int a= 0; a < 100; a++) for(int b = 0; b< 100; b++) { Creature empty_creature = Creature(*empty,a,b,NORTH,this); (Grid::map)[a][b] = empty_creature; } } int main() { Grid world = Grid(8,8); } class Grid { protected: Creature map[100][100]; int width,height; int turn_number; Species *empty; Species *wall; public: Grid(); Grid(int _width, int _height); void addCreature(Species &_species, int x, int y, Direction orientation); void addWall(int x, int y); void takeTurn(); void infect(int x, int y, Direction orientation, Species &_species); void hop(int x, int y, Direction orientation); bool ifWall(int x, int y, Direction orientation); bool ifEnemy(int x, int y, Direction orientation, Species &_species); bool ifEmpty(int x, int y, Direction orientation); void print(); }; class Species { protected: int program_length; string program[100]; string type; public: species(string _type); void addInstruction(string instruction); bool isWall(); bool isEmpty(); bool isEnemy(Species _enemy); string instructionAt(int index); string getType(); };

    Read the article

  • Enumerations and String values in ASP.NET

    - by Jason
    I'm looking for some best practice advice on enumerations and retrieving an associated string value. Given this: public enum SerialKillers { TedBundy, EdGein, AlbertFish, GeorgeBush } What is the best way to get a related string value of the name? Eg. "Ted Bundy", given that the string value may not match the representation in the enumeration. eg "George W Bush" My current thinking is function accepting an enum and returning a string, but would that not mean hard coding the string values (which I prefer not to do)? Is using a resources file where the string can be retrieved via the enumeration too heavy handed? Should I accept the fact I am going to Hell for victimising Ted Bundy by associating him with George Bush?

    Read the article

  • Convert From Custom List to List of String

    - by Paul Johnson
    Hi all I have the following code: Public Shared Function ConvertToString(ByVal list As IList) As String Dim strBuilder = New System.Text.StringBuilder() Dim item As Object For Each item In list strBuilder.Append(obj.ToString()) strBuilder.Append(",") Next Return strBuilder.ToString(strBuilder.Length - 1) End Function The intention is to convert an IList of custom objects to a string equivalent comprising each element in the Ilist. Unfortunately I can't seem to find a way to get the underlying data of the custom object, and of course as in the above example, using object simply gives me a string of types definitions, rather than access to the underlying data. Any assistance much appreciated. Paul.

    Read the article

  • Replace letters in a secret text

    - by kame
    Hello! I want to change every letter in a text to after next following letter. But this program doesnt work. Does anyone know why. Thanks in advance. There is also a minor problem with y and z. import string letters = string.ascii_lowercase text=("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj. ") for x in range(1,24): text.replace(letters[x],letters[x+2]) print(text)

    Read the article

  • string replace in file using C

    - by Hristo
    I haven't yet implemented this, I'm still in the thinking stage, but I have to go through a file and replace a certain string with another string. For example, <img src="/images/logo.gif" ... should become <img src="/proxy/www.example.com/images/logo.gif" ... Any advice on how I can approach this? Perhaps there exist some "string replace" C functions that would do this for me that I don't know about...? Right now, if I had to write this function myself, I would give it as parameters the file, string to replace, replacement string. Then I would manually go through the file and look for an occurrence of the string and recreate it. This, however, seems very inefficient. Are there better ways to do this? Thanks, Hristo

    Read the article

  • Hyphenate a random string to an exact format

    - by chrissygormley
    Hello, I am creating a random ID using the below code: from random import * import string # The characters to make up the random password chars = string.ascii_letters + string.digits def random_password(): return "".join(choice(chars) for x in range(32)) This will output something like: 60ff612332b741508bc4432e34ec1d3e I would like the format to be in this format: 60ff6123-32b7-4150-8bc4-432e34ec1d3e I was looking at the .split() method but can't see how to do this with a random id, also the hyphen's must be at these places so splitting them by a certain amount of digits is out. I'm asking is there a way to split these random id's by 8 number's then 4 etc. Thanks

    Read the article

  • Splitting only long words in string

    - by owca
    I have some random string, let's say : s = "This string has some verylongwordsneededtosplit" I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted. The result should be something like that str = trunc_string(s, 10) str = "This string has some verylongwo rdsneededt osplit" For now I have something like this : def truncate_long_words(s, num): """Splits long words in string""" words = s.split() for word in words: if len(word) > num: split_words = list(words) After this part I have this long word as a list of chars. Now I need to : join 'num' chars together in some word_part temporary list join all word_parts into one word join this word with the rest of words, that weren't long enough to be splitted. Should I make it in somehow similar way ? : counter = 0 for char in split_words: word_part.append(char) counter = counter+1 if counter == num And here I should somehow join all the word_part together creating word and further on

    Read the article

  • Javascript Getting a string into kb format

    - by Teske
    I am new to javascript and I just wanted to convert a string into a format that a person like me can read. Here is an example of what I am trying to do... string2size(string){ //some awesome coding I have no clue how to make return awesomeAnswer } now the return should give me something like 56 bytes or 12kb or 1mb depending how much the string is. so if the string is... string = "there was an old woman who lived in a shoe"; then string2size(string) should return something like 3kb. Now I know there has been a utf8 talk and I wouldn't object to and addition of that to the function. I have tried google and Yahoo searches but they talk of using php but I really need it for javascript. I do thank anyone for their time. -Teske

    Read the article

  • Path String Concatenation Question in C#.

    - by Nano HE
    Hello. I want to output D:\Learning\CS\Resource\Tutorial\C#LangTutorial But can't work. Compiler error error CS0165: Use of unassigned local variable 'StrPathHead Please give me some advice about how to correct my code or other better solution for my case. Thank you. static void Main(string[] args) { string path = "D:\\Learning\\CS\\Resource\\Book\\C#InDeepth"; int n = 0; string[] words = path.Split('\\'); foreach (string word in words) { string StrPathHead; string StrPath; Console.WriteLine(word); if (word == "Resource") { StrPath = StrPathHead + word + "\\Tutorial\\C#LangTutorial"; } else { StrPathHead += words[n++] + "\\"; } } }

    Read the article

  • Modify strings in Rails?

    - by Daniel O'Connor
    Hey everyone, So I'm new to Rails (teaching myself as a senior project in high school), and I'm trying to figure out how to modify these strings. Let's say someone writes the following string in a form: "you know you are a geek when" How can I automatically change it to this: "You know you are a geek when..."? I need Rails to check the case of the first letter and check for the three dots then modify the string as necessary. I've looked here, but I can't find anything that would work. Thanks a lot!

    Read the article

  • Fastest way to put contents of Set<String> to a single String with words separated by a whitespace?

    - by Lars Andren
    I have a few Set<String>s and want to transform each of these into a single String where each element of the original Set is separated by a whitespace " ". A naive first approach is doing it like this Set<String> set_1; Set<String> set_2; StringBuilder builder = new StringBuilder(); for (String str : set_1) { builder.append(str).append(" "); } this.string_1 = builder.toString(); builder = new StringBuilder(); for (String str : set_2) { builder.append(str).append(" "); } this.string_2 = builder.toString(); Can anyone think of a faster, prettier or more efficient way to do this?

    Read the article

  • Java multiline string

    - by skiphoppy
    Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code: $string = <<"EOF" # create a three line string text text text EOF In Java I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch. What are some better alternatives? Define my string in a properties file? Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for away around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls. Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.

    Read the article

  • How do I truncate a .NET string?

    - by Steve Guidi
    I apologize for such a question that likely has a trivial solution, but I strangely could not find a concise API for this problem. Essentially, I would like to truncate a string such that it its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype. For instance, it would be nice if I could write the following: string NormalizeLength(string value, int maxLength) { return value.Substring(0, maxLength); } Unfortunately, this raises an exception because maxLength exceeds the string boundaries. Of course, I could write a function like the following, but I was hoping that something like this already exists. string NormalizeLength(string value, int maxLength) { return value.Length <= maxLength ? value : value.Substring(0, maxLength); } Where is the elusive API that performs this task? Is there one?

    Read the article

  • Split string into smaller part with constrain [PHP RegEx HTML]

    - by Sadi
    Hello, I need to split long string into a array with following constrains: Each part will have a limited number of character (e.g. not more than 8000 character) Each part can contain multiple sentences (delimited by . [full stop]) but never a partial sentences. Except if the last part of the string (as last part may not have any full stop. The string may contain HTML tags. But the tag can not be divided as ( to ). That means HTML tag should be intact. But starting tag and ending tag can be stay on different segment/chunk. I think regular expression with preg_split can do it. Would please help me with the proper RegEx. Thank you Sadi

    Read the article

  • About the String#substring() method

    - by alain.janinm
    If we take a look at the String#substring method implementation : new String(offset + beginIndex, endIndex - beginIndex, value); We see that a new String is created with the same original content (parameter char [] value). So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist). I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead? The other related question is : should we always use new String(...) when dealing with substring?

    Read the article

  • Split string var

    - by lidermin
    Hi, I have a question: Let's say I have this string var: string strData = "1|2|3|4||a|b|c|d" Then, I make a Split: strNumbers[] = strData.Split("||"); //something like this, I know It's not this simple I need two separate parts, each one containing this: //strNumbers -> {"1","2","3","4"},{"a","b","c","d"} So that after that, I could do this: string[] strNumArray[] = strNumbers[0].Split('|'); //strNumArray -> '1', '2', '3', '4' And same with the other part (letters). Is it possible? to make this double split with the same character, but the first time the character is repeated twice?. Thanks. PD. I'm using C#.

    Read the article

  • String intern puzzles

    - by Yob
    On this blog I found interesting String puzzles: --- Quote --- String te = "te", st = "st"; //"test".length(); String username = te + st; username.intern(); System.out.println("String object the same is: " + (username == "test")); prints String object the same is: true but uncomment the "test".length(); line and it prints String object the same is: false --- EoQ --- Being honest I don't understand why the outputs are different. Could you please explain me what's the cause of such behaviour?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >