views:

37

answers:

1

Hello I am a newbiew to java.

I am trying to write an macroresolver I have string which is represneted as

String s = '{object.attribute}'  --> result of the resolver should be 'attribute'

String prefix = '{object.'
String suffix = '}'

that was easy.

i also want to extend to use the same resolver to resolve the following

String s = 'attrName1=$attrValue1$;&attrName2=$attrValue2$;'  --> result of the resolver should be attrName1=attrValue1;&attrName2=attrValue2;

String prefix = '$'
String suffix = '$'

i can have a greneralized prefix and suffix passed to the method but not sure what the logic should be.

public class StringMacro {

/**
 * @param args
 */
public static void main(String args[]) {
    String s = "{article.article_type}";
    String prefix = "{article.";
    String suffix = "}";
    int prefixLength = prefix.length();
    int suffixLength = suffix.length();
    int startIndex = s.indexOf("{article.");
    int prevEndIndex =startIndex+s.indexOf(suffix);

    StringBuffer output = new StringBuffer();

    while (startIndex != -1 ) {
        output.append(s.substring(startIndex+prefixLength,prevEndIndex));
        int endIndex = s.indexOf(suffix,startIndex);
        if ( endIndex == -1 ) {
            output.append(s.substring(startIndex));
            break;
        }
        String macro = s.substring(startIndex+prefixLength,endIndex-1);

        prevEndIndex = endIndex+suffixLength;
        startIndex = s.indexOf(prefix, prevEndIndex);


    }

    System.out.println(">>>"+output);
}

}

Help Please!!!!!

A: 

this should probably do the trick.

public static void main(String args[]) {
    String s = "attr1=$attr1Value$&attr2=$attr2Value$Test"String;
    String prefix = "$";
    String suffix = "$";

    String s1 = "{obj.attr}";
    String prefix1 = "{obj";
    String suffix1 = "}";

    int prefixIndex = 0;
    int startIndex = 0;
    int endIndex = 0;
    Map map = new HashMap();
    map.put("attr1Value", "100W");
    map.put("attr2Value", "123W");
    map.put("attr", "columnist");


    StringBuffer buffer = new StringBuffer();
    while(prefixIndex != -1){
        prefixIndex = s.indexOf(prefix, prefixIndex);
        endIndex = s.indexOf(suffix, prefixIndex+prefix.length());

        buffer.append(s.substring(startIndex, prefixIndex));

        if(endIndex == -1){
            break;
        }
        System.out.println(s.substring(prefixIndex+prefix.length(), endIndex));
        buffer.append(map.get(s.substring(prefixIndex+prefix.length(), endIndex)));

        prefixIndex = s.indexOf(prefix, endIndex+suffix.length());

        startIndex= endIndex+suffix.length();
    }

    if(prefixIndex == -1){
        buffer.append(s.substring(endIndex+suffix.length()));
    }

    System.out.println(buffer);






}

}

Shah