How to substring by bytes

Hi,
I need to save strings in different langauges in the DB, up to 24 bytes.
How can i substring by bytes in java?
for example:
Èçðàèëü - is 14 bytes, but the string length is 7
hhhhhhh - is 7 bytes and the string length is 7.
i would like to cut it by bytes - up to 7 bytes.
if i use substring method, i get 14 bytes for the Russian letters!
how can i do it?
Thanks!

Find out what encoding your database uses.
Based on that, you can encode a character at a time to bytes (using String.valueOf(character).getBytes(encoding)) and count the bytes used.
When the required number of bytes are reached, return the string so far:
import java.nio.charset.Charset;
public class StringTrimToBytes {
        final Charset     charset;
        public StringTrimToBytes (String charsetName) {
                charset = Charset.forName(charsetName);
        public String trim (String string, int byteLength) {
                for (int index = 0, len = string.length(), bytes = 0; index < len; ++index) {
                        bytes += String.valueOf(string.charAt(index)).getBytes(charset).length;
                        if (bytes > byteLength)
                                return string.substring(0, index);
                return string;
        public static void main (String...args) {
                final StringTrimToBytes trimmer = new StringTrimToBytes("UTF-8");
                for (String arg : args)
                        System.out.println(trimmer.trim(arg, 5));
}But quite how you explain the behaviour to your users might be a bit tricky - "why can I put my address in if I don't spell the street name with an accent, but not otherwise?"

Similar Messages

  • How to Substr field in SAP Query.

    Dear Developer,
    How to substr any field in SAP Query ?
    Regards,
    Ujed.

    Hi Ujed,
    if SUBSTR stands for substring, then possibly your question may be how to get the substr method as konown in languages like php in ABAP.  If SAP Query points to a SAP query as created in transaction SQ01, then you should explain what you want to achieve.
    Note: Better ask a specific question and get am answer you can or which is already generalized.
    If I need a substr function, I'd create a functional method for that:
    method substr
      importing
        anyfield type any
        offset type i
        length type i
      returning substring type string.
      try.
        substring = anyfield+offset(length).
      catch cx_root.
    * handle error
      endtry.
    endmethod.
    Regards,
    Clemens

  • How to display double byte characters with system.out.print?

    Hi, I'm a newbie java programmer having trouble to utilize java locale with system io on dos console mode.
    Platform is winxp, jvm1.5,
    File structure is:
    C:\myProg <-root
    C:\myProg\test <-package
    C:\myProg\test\Run.java
    C:\myProg\test\MessageBundle.properties <- default properties
    C:\myProg\test\MessageBundle_zh_HK.properties <- localed properties (written in notepad and save as Unicode, window notepad contains BOM)
    inside MessageBundle.properties:
    test = Hello
    inside Message_zh_HK.properties:
    test = &#21890; //hello in big5 encoding
    run.java:
    package test;
    import java.util.*;
    public class Run{
      public static void main(String[] args){
        Locale locale = new Locale("zh","HK");
        ResourceBundle resource =
            ResourceBundle.getbundle("test.MessageBundle", locale);
        System.out.println(resource.getString("test"));
      }//main
    }//classwhen run this program, it'll kept diplay "hello" instead of the encoded character...
    then when i try run the native2ascii tool against MessageBundle_zh_HK.properties, it starts to display monster characters instead.
    Trying to figure out what I did wrong and how to display double byte characters on console.
    Thank you.
    p.s: while googling, some said dos can only can display ASCII. To demonstrate the dos console is capable of displaying double byte characters, i wrote another helloWorld in chinese using notepad with C# and compile using "csc hello.cs", sure enough, console.write in c# allowed me to display the character I was expecting. Since dos console can print double byte characters, I must be missing something important in this java program.

    after google a brunch, I learned that javac (hence java.exe) does not support BOM (byte order mark).
    I had to use a diff editor to save my text file as unicode without BOM in order for native2ascii to convert into a ascii file.
    Even the property file is in ascii format, I'm still having trouble to display those character in dos console. In fact, I just noticed I can use system.out.println to display double byte character if I embedded the character itself in java source file:
    public class Run {
         public static void main(String[] args) throws UnsupportedEncodingException{
              String msg = "&#20013;&#25991;";    //double byte character
                    try{
                    System.out.println(new String(msg.getBytes("UTF-8")) + " new string");  //this displays fine
                    catch(Exception e){}
                    Locale locale = new Locale("zh", "HK");
              ResourceBundle resource = ResourceBundle.getBundle("test.MessagesBundle", locale);
                    System.out.println(resource.getString("Hey"));      //this will display weird characterso it seems like to me that I must did something wrong in the process of creating properties file from unicode text file...

  • How to transform a byte[] variable to a Integer variable?

    Can anybody do me a favor to tell me how to trasform a byte[]variable to a Integer or String variable?
    Thank you very much

    To transform a bytearray to a string is simple:
    String s = new String(byteArray);Transforming an bytearray to an Integer isn't that simple... I don't know the best way to do it. But one way is to transform it to a String and then:
    Integer i = new Integer(new String(byteArray));//David

  • How to get the byte[] size dynamically from the StreamMessage object

    Hi all,
    Using JMS, I am receiving the FDF file as StreamMessage from the queue and attaching it to the PDF file which is present in the local system.
    For that, I have written the code as follows:
    {color:#0000ff} Message msg = jmsTemplate.receive();
    if(msg !=null && msg instanceof StreamMessage)
    StreamMessage message = (StreamMessage) msg;{color}
    {color:#ff6600}//hardcoded the byte array size value
    {color}{color:#0000ff} byte[] bytes = new byte[{color:#ff0000}856{color}];
    System.out.println("read msg="+message.readBytes(bytes));{color}
    {color:#0000ff}PdfReader pdfreader = new PdfReader("D:\\Managing_Workflows_No_Comment.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream("D:\\12345.pdf"));
    FdfReader fdfreader = new FdfReader(bytes);
    stamp.addComments(fdfreader);
    {color} {color:#0000ff} stamp.close();
    {color}{color:#000000}The above code is working fine except with the hardcoded of {color:#ff0000}byte array{color}{color:#ff0000} size value{color} which is given in {color:#ff0000}RED{color} in color.
    Can anybody know, {color:#000000}*how to get the byte[] size dynamically from the StreamMessage*{color} object ?
    Any help would be highly beneficial for me !!!!
    Thanks and Regards,
    Ganesh Kumar{color}

    When you create your stream message you could add an property to your message, something like streamSize that would contain the number of bytes in your stream message. Then you could get this property from the message before declaring your array.
    Tom

  • Multiplatform: how convert int into byte[]???

    Hi all,
    I need to convert an int value into an array of bytes. An int is represented by 4 bytes, but the problem is that depending on the platform, the most significant byte is the first or the last, so if you convert it directly, like:
    int i = 5;
    byte b[] = new byte[4];
    b[0] = (byte)( (i & 0xff000000) >>> 24);
    b[1] = (byte)( (i & 0x00ff0000) >>> 16);
    b[2] = (byte)( (i & 0x0000ff00) >>> 8);
    b[3] = (byte)( (i & 0x000000ff) );
    you cannot export it to another platfroms.
    Thank you in advance.

    Come on, nobody knows how to detect the byte order in a given platform?
    I've been all the day dealing with this, which means all day without producing.
    Please, it�s very urgent.
    Thank you again.

  • How can I manage byte size of a string value in java?

    Hi,
    How can I manage byte size of a string value in java? I have NAME column in my database table, of type VARCHAR2(128). Supports multilingual, so value in Name can be English, French or Dutch.. like that. Byte size of English character is 1 and that of French is 2 and varies.. . Because of this reason I find difficulty in insert query. Please suggest solution.

    But the event does not really have a size - you can export the photos and make the size pretty much what you want - while it is in iPhoto it is an event
    I guess that iPhoto could report the size of the original photos as imported - or the size of the modified photos if exported as JPEGs - or the size of the modified photos if exported with a maximum dimension of 1080 - but the event simply is photos and does not have a "size" until you export it
    Obviously you want to know the size but the question was
    what is your puprose for knowing the size?
    WIth that information maybe there is a way to get you what you want
    But the basic answer is simply that an event does not have a size - an event is a collection of photos and each photo has either two or three versions in the iPhoto library and each photo can be exported for outside use in several formats and at any size
    LN

  • How to calculate the byte tranfer to the http server

    Hi,
    I'm developing a multiplayer game on mobile phone.
    At the end of the connexion, I need to know how many bytes were sent and received from the http server.
    Here is the part code for the connexion to the server :
    HttpConnection connection = (HttpConnection)Connector.open(request);
    connection.setRequestMethod(HttpConnection.GET);
    InputStream is = connection.openInputStream();
    long length = connection.getLength();
    byte[] datach = new byte[1];
    int ch = 0;
    while(is.read(datach) != -1)
         ch = datach[0];
         b.append((char)ch);
    String s = b.toString();The size of each data I have to send or receive is less than 50 bytes.
    All I do for now is adding the request size and the server response size.
    For each request, I have to count the header size and the data size. But I don't know how to find the header size of my request.
    And for each response from the server, I count the header size and the data size with connection.getLength().
    I don't know whether it's the right method.
    Does anyone know a better method to calculate exactly the bytes sent and received?

    TCP/IP "overhead" is basically 20%.

  • How to skip audio bytes from AudioInputStream??

    Hi all,
    I am trying to write a web application to analyze the frequency spectrum of an audio file. The user has a field of a html-form to enter the time point, that he wants to analyze. According to the user input the frequency spectrum will be analyzed. The current position of the audio file should be calculated first according to this time point. And then the samples after this position from the Audio will be read and then be gathered into an Array. At the end they will be transformed with FFT.
    My problem ist that i must read the samples from the first byte of the AudioInputStream (using the read-Method of the AudioInputStream) by every analyze, until the position has been reached. For a long audio file and wenn the user wants to analyze the spectrum of the end of the file, it will take so much time!!
    Does anyone know, how can i directly skip the samples before the position and begin the Gathering immediately? the skip-Method of AudioInputStream doesn't work fine! it can't skip to the position correctly.
    Thanx in Advance

    i tried to use this to skip the bytes: Method 1
    AudioInputStream stream_in = AudioSystem.getAudioInputStream("c:\\\\a.wav");
    byte[] audioBytes = new byte[4096];
    int bytesToSkip = 200000 // just for example
    int bytesRead = 0;
    try {
    while ((bytesRead = stream_in.read(audioBytes)) != -1) {
    bytesToSkip -= bytesRead;
    if (bytesToSkip <= 0) {
    }catch (Exception e) {
    e.printStackTrace(System.out);
    This method takes to much time, if i want to skip to the end of an long audio file.
    Then i tried to use skip() method of AudioInputStream: Method 2
    AudioInputStream stream_in = AudioSystem.getAudioInputStream("c:\\\\a.wav");
    int bytesToSkip = 200000 // just for example
    int loops = 100
    try {
    while (bytesToskip >0 && loops>0) {
    bytesToSkip -= stream_in.skip(bytesToSkip);
    loops --;
    }catch (Exception e) {
    e.printStackTrace(System.out);
    //the bytes have been skipped and begin with the manipulation:
    The problem hier is, that the skip method may end up skipping over much smaller number of bytes, possibly 0.
    Can anyone tell me, how can i accelerate the method 1 or how can i fix the skip method in method 2. Or any other options?
    Thanx again!!

  • How to turn a byte[] into an image?

    My app downloads image data from a server, storing the data in a byte[] called imageDataByteArray.
    I want to use imageDataByteArray to create an image. For this, I have tried using:
    int w = imageWidth; //488
    int h = imageHeight; //245
    int imageOffset = 0;
    int scan = w;
    Image image = component.createImage(new MemoryImageSource(w, h, java.awt.image.ColorModel.getRGBdefault(), imageDataByteArray, imageOffset, scan));
    ...but the image created is empty.
    I think the length of imageDataByteArray is a problem - it's length is only 21461, whereas the number of pixels in the image ( = imageWidth * imageHeight) is 119560.
    I've played around for a while, but cannot solve. Can anyone help?

    Hiya Rodney,
    Yes, it's in jpg format. I've tried your code but the image does not display correctly.
    To shed some more light, here's how I'm getting the image:
    I am using standard http code to connect to the image url (http://www...../image.jpg) which returns the image data as a String, called httpContent. I then convert this String to imageDataByteArray with httpContent.getBytes[] - but am obviously struggling to recreate the image.
    Any ideas where I might be going wrong?
    Thanks,
    James

  • How to set Multi Byte Character Set ( MBCS ) to Particular String In MFC VC++

    I Use Unicode Character Set in my MFC Application ( VC++) .
    now i get the output   ठ桔湡潹⁵潦⁲獵 (like this )character and i want to convert this character in english language (means MBCS),
    But i need Unicode to My Applicatiion. when i change the Multi-Byte Character set It give Correct output in English but other Objects ( TreeCtrl Selection ) will perform wrongly .  so i need to convert the particular String to MBCS
    how can i do that ? In MFC

    I assume your string read from your hardware device is an plains "C" string (ANSI string). This type of string has one byte per character. Unicode has two bytes per character.
    From the situation you explained I'd convert the string returned by the hardware to an Unicode string using i.e. MultibyteTowideChar with CP_ACP. You may also use mbstowcs or some similar functions to convert your string to an Unicode string.
    Best regards
    Bordon
    Note: Posted code pieces may not have a good programming style and may not perfect. It is also possible that they do not work in all situations. Code pieces are only indended to explain something particualar.

  • How to make my byte unsigned to send with datagrampacket

    Hello I have a problem with signed and unsigned.
    I know java doesn't use unsigned.
    But I need to send a datagrampacket to a computer that runs with a c program.
    With datagrampacket you need to send a byte array.
    The data I send now contains unsigned bytes but the c program only want signed.
    Now I have something like this
    data[0]=31;
    data[1]=64;
    data[2]=-102;
    etc.
    I found this in the forum to make a byte unsigned.
    int i = i >= 0 ? i : 256 + 1;
    But my problem is that the byte becomes an int and I need a byte.
    I hope someone can help

    If I send time 10:12:40 the computer time changes in the send value.If you send a value, whether a time or not, the value should not change automagically.
    When I do this with my c program at clientside to the c program at serverside the value changes.How does it change, why does it change,
    Should not the server receive the same packet as was sent?
    But when I do this with my java code I receive a packet from the server but nothing changed This is what I would have expected.
    and the only difference between the package I send is that the c program send everything unsignedThe network has no concept of signed or unsigned. Everything is just a stream of 8-bit values called octects. Nothing more. To say the client send the data unsigned is not a meaningful distinction.

  • JDO : how to map a byte array field correctly

    Could someone please provide an example on how to correctly map a byte array field in a PCClass.
    The field should be mapped to a BLOB field in my Dictionary project.
    The checker keeps throwing errors during the enhancement process. Tried all sorts of combinations of xml in my jdo and map file (using the dtd) but I still haven't found the solution. The compilation works fine though, it is only the checker that complains.

    You're already in a PDF open in Acrobat (not the free Adobe Reader) and you've made a new PDF? Which you want to save to disk and reopen?

  • How can I uses byte[] to represent the length of a message?

    hihi,
    I want to using 3-bytes to represent the length of a message that send over a socket,
    I don't know how to using byte to represent the length, should I parse integer to byte?
    thank you

    int length;
    DataOutputStream dos = ...;
    dos.writeByte(length >>> 16);
    dos.writeByte(length >>> 8);
    dos.writeByte(length & 0xff);But why 3? Why not 2 or 4 like everybody else? with DataOutputStream.writeShort() or writeInt()?

  • How to Substring from the last 3rd underscore?

    Hi Friends,
    I have so many strings like as given below.
    PRINT_IB_0_10009473330100_I000001_FILE001_1.txt
    I have to substring the value starting from last 3rd underscore to extension dot. e.g. I need a
    output like I000001_FILE001_1 from the above given string.
    Thanks in advance...
    - Hiren Modi

    Well, you could use lastIndexOf three times (with the start position option) but I think it looks more like a job for a regular expression (which could also check if the file name has the pattern you're expecting.)
    You might want a pattern like "[A-Z][0-9]_{6}[A-Z0-9]*_[0-9]\.txt$", depends how much these file names are expected to vary.

Maybe you are looking for

  • Can not open the completed task.

    Hi, All.      I config my uwl to accept the GP tasks.      It works fine with the tasks which is in process.      I can click the link and deal with the gp task successfully.      When I switch to the completed tasks, I can see the tasks which I fini

  • I am trying to figure out why my Apple ID is not working properly.

    So at first i was trying to install some new apps from the app store on my iphone 4. And a message box kept popping up saying i needed to "agree to itunes terms of use" and so i would click on it so that i could agree and there was a little box that

  • SlingBox in Windows7 Safari plug-in update..... help.......

    I run Sling box sometimes in the Windows 7 format, I'm wanting to use Safari as my Application of choice, hence the rub. When attempting to connect I get a plug-in update message for Safari, I accept the terms of use. and I get nothing.........no dow

  • Error on RAC failover process

    Dear All, i am using oracle 10.2.04 RAC configured database and below is my TNS entry. ORCL = (DESCRIPTION_LIST = (LOAD_BALANCE = OFF) (FAILOVER = ON) (DESCRIPTION = (ADDRESS_LIST = (LOAD_BALANCE = ON) (FAILOVER = ON) (ADDRESS = (PROTOCOL = TCP)(HOST

  • Only one page on my website Firefox can not open

    Hello, On my website I have four pages. Firefox opens three up and not the other. The one in question opens for a split second then Firefox reverts back to downloading. No messages appear to indicate a problem. Google Chrome opens up all four pages b