Splitting a string into 4 equal parts
Hi All,
I have a string with maximum no of characters as 100,
I want to split this string into 4 equal parts.
Any help will be appreciated.
Regards
Hi Rajeev,
Use this sample code
class SplitString {
public static void main(String[] arguments) {
StringTokenizer ex1, ex2; // Declare StringTokenizer Objects
int count = 0;
String strOne = "one two three four five";
ex1 = new StringTokenizer(strOne); //Split on Space (default)
while (ex1.hasMoreTokens()) {
count++;
wdComponentAPI.getMessageManager().reportSuccess("Token " + count + " is" + ex1.nextToken() );
count = 0; // Reset counter
String strTwo = "item one,item two,item three,item four"; // Comma Separated
ex2 = new StringTokenizer(strTwo, ","); //Split on comma
while (ex2.hasMoreTokens()) {
count++;
wdComponentAPI.getMessageManager().reportSuccess("Token " + count + " is "+ ex2.nextToken() );
Thanks
Anup
Edited by: Anup Bharti on Oct 27, 2008 12:36 PM
Similar Messages
-
Splitting a string into multiple parts from particular position (string has no delimiter )
Hello Gurus,
I need to make string of having length 1000 into multiple parts from a particular position which has some text without any delimiter and i want to populate each part into an internal table which has one filed...
eg : string = 'sap abap sap abap sap abap sap abap sap abap sap abap sap abap sap sap sap abap sap abap'
suppose i want to start splitting from 40th position...assume that i have 3 parts
and these 3 parts i have put into an internal table..
lt_itab = [sap abap sap abap sap abap sap abap,
sap abap sap abap sap abap sap abap,
sap abap sap sap sap abap sap abap]
plese help!
any help would be Appreciated ...thank youHi,
Try this code.
TYPES: BEGIN OF ty,
b TYPE string,
END OF ty,
tt TYPE STANDARD TABLE OF ty.
DATA: a TYPE string VALUE 'aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll',
tb TYPE tt,
wa TYPE ty,
off TYPE i,
len TYPE i,
count TYPE i,
count1 TYPE i,
temp TYPE i.
len = 8. "Position
off = 0.
count = strlen( a ).
count1 = count / 8.
temp = len - 1.
DO count1 times.
temp = off + len.
IF temp > count.
wa-b = a+off.
ELSE.
wa-b = a+off(len).
ENDIF.
off = off + len.
SHIFT wa-b LEFT DELETING LEADING space.
APPEND wa to tb.
ENDDO.
LOOP AT tb INTO wa.
write: / wa-b.
ENDLOOP. -
Which match gets used when you use OR ('|') to specify multiple possible matches in a regex, and there are multiple matches among the supplied patterns? The first one (in the order written) which matches? Or the one which matches the most characters?
To make this concrete, suppose that you want to split a String into lines, where the line delimiters are the same as the [line terminators used by Java regex|http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#lt] :
A newline (line feed) character ('\n'),
A carriage-return character followed immediately by a newline character ("\r\n"),
A standalone carriage-return character ('\r'),
A next-line character ('\u0085'),
A line-separator character ('\u2028'), or
A paragraph-separator character ('\u2029)
This problem has [been considered before|http://forums.sun.com/thread.jspa?forumID=4&threadID=464846] .
If we ignore the idiotic microsoft two char \r\n sequence, then no problem; the Java code would be:
String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]");How do we add support for \r\n? If we try
String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]|\\r\\n");which pattern of the compound (OR) regex gets used if both match? The
[\\n\\r\\u0085\\u2028\\u2029]or the
\\r\\n?
For instance, if the above code is called when
s = "a\r\nb";and if the first pattern
[\\n\\r\\u0085\\u2028\\u2029]is used for the match when the \r is encountered, then the tokens will be
"a", "", "b"
because there is an empty String between the \r and following \n. On the other hand, if the rule is use the pattern which matches the most characters, then the
\\r\\n
pattern will match that entire \r\n and the tokens will be
"a", "b"
which is what you want.
On my particular box, using jdk 1.6.0_17, if I run this code
String s = "a\r\nb";
String[] lines = s.split("[\\n\\r\\u0085\\u2028\\u2029]|\\r\\n");
System.out.print(lines.length + " lines: ");
for (String line : lines) System.out.print(" \"" + line + "\"");
System.out.println();
if (true) return;the answer that I get is
3 lines: "a" "" "b"So it seems like the first listed pattern is used, if it matches.
Therefore, to get the desired behavior, it seems like I should use
"\\r\\n|[\\n\\r\\u0085\\u2028\\u2029]"instead as the pattern, since that will ensure that the 2 char sequence is first tried for matches. Indeed, if change the above code to use this pattern, it generates the desired output
2 lines: "a" "b"But what has me worried is that I cannot find any documentation concerning this "first pattern of an OR" rule. This means that maybe the Java regex engine could change in the future, which is worrisome.
The only bulletproof way that I know of to do line splitting is the complicated regex
"(?:(?<=\\r)\\n)" + "|" + "(?:\\r(?!\\n))" + "|" + "(?:\\r\\n)" + "|" + "\\u0085" + "|" + "\\u2028" + "|" + "\\u2029"Here, I use negative lookbehind and lookahead in the first two patterns to guarantee that they never match on the end or start of a \r\n, but only on isolated \n and \r chars. Thus, no matter which order the patterns above are applied by the regex engine, it will work correctly. I also used non-capturing groups
(?:X)
to avoid memory wastage (since I am only interested in grouping, and not capturing).
Is the above complicated regex the only reliable way to do line splitting?bbatman wrote:
Which match gets used when you use OR ('|') to specify multiple possible matches in a regex, and there are multiple matches among the supplied patterns? The first one (in the order written) which matches? Or the one which matches the most characters?
The longest match wins, normally. Except for alternation (or) as can be read from the innocent sentence
The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.
in the javadocs. More information can be found in Friedl's book, the relevant page of which google books shows at
[http://books.google.de/books?id=GX3w_18-JegC&pg=PA175&lpg=PA175&dq=regular+expression+%22ordered+alternation%22&source=bl&ots=PHqgNmlnM-&sig=OcDjANZKl0VpJY0igVxkQ3LXplg&hl=de&ei=Dcg7S43NIcSi_AbX-83EDQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CA0Q6AEwAA#v=onepage&q=&f=false|http://books.google.de/books?id=GX3w_18-JegC&pg=PA175&lpg=PA175&dq=regular+expression+%22ordered+alternation%22&source=bl&ots=PHqgNmlnM-&sig=OcDjANZKl0VpJY0igVxkQ3LXplg&hl=de&ei=Dcg7S43NIcSi_AbX-83EDQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CA0Q6AEwAA#v=onepage&q=&f=false]
If this link does not survive, search google for
regular expression "ordered alternation"
My first hit went right into Friedl's book.
Harald. -
How to split this string into 4 sections to a max 35 characters
Hello,
Does anyone have an idea how I can acheive this please.
I have this string
Expense_Inv_8- ExpenseInv_7- Exp001- Expense_Inv_6- Expense_Inv_5- Expense_Inv_4- Expense_Inv_3- Expense_Inv_2- Expense_inv1
and I need to display them in sections seperated by ';' as explained below
Section 1 Section 2 Section 3 Section 4
Expense_Inv_8- ExpenseInv_7- Exp001;Expense_Inv_6- Expense_Inv_5;Expense_Inv_4- Expense_Inv_3;Expense_Inv_2;
need to split this string into 4 sections seperated by ';' and each section should be of no more than 35 characters, if null should end ;;;
Section 1, 35 Character ended by;
Section 2, broken off after Expense_Inv_5 because Expense_Inv_4 will take it over 35 chracters)
Section 3, should only take Expense_Inv_4- Expense_Inv_3, because adding Expense_Inv_2 will take it over 35
characters, each record in the string is seperated by '-'
Section 4, dispays the reminder of the string
regards
AdeHi,
Welcome to the forum!
Whenever you ask a question, it helps if you post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) and the results you want from that data.
I think I understand the problemk well enough to attempt a solution, but if the query below isn't right, please post that information.
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= ( SELECT MAX (LENGTH (txt))
FROM table_x
, got_best_path AS
SELECT id
, txt
, MAX ( SYS_CONNECT_BY_PATH ( TO_CHAR (c.n, '99')
) AS best_path
FROM cntr c
JOIN table_x x ON c.n <= LENGTH (x.txt)
START WITH c.n = 1
CONNECT BY c.n - PRIOR c.n BETWEEN 1
AND :section_length
AND x.id = PRIOR x.id
AND SUBSTR ( x.txt
, c.n
, 1
) = '-'
AND LEVEL <= :section_cnt
GROUP BY id
, txt
, got_pos AS
SELECT id
, REPLACE ( txt
) || ';' AS txt
, best_path
, TO_NUMBER (REGEXP_SUBSTR (best_path, '[0-9]+', 1, 2)) AS pos_2
, TO_NUMBER (REGEXP_SUBSTR (best_path, '[0-9]+', 1, 3)) AS pos_3
, TO_NUMBER (REGEXP_SUBSTR (best_path, '[0-9]+', 1, 4)) AS pos_4
FROM got_best_path
SELECT id
, SUBSTR (txt, 1 , NVL ( pos_2 , :section_length)) AS section_1
, SUBSTR (txt, pos_2 + 1, NVL ((pos_3 - pos_2), :section_length)) AS section_2
, SUBSTR (txt, pos_3 + 1, NVL ((pos_4 - pos_3), :section_length)) AS section_3
, SUBSTR (txt, pos_4 + 1, :section_length ) AS section_4
FROM got_pos
;As written, this requires SQL*Plus 9 (or higher). You can have multiple versions or SQL*Plus on the same client, if you really need to keep the older version.
:section_length is the maximum length of each section (35, as you stated the problem).
:section_cnt is the number of sections. In the query above, this is 4. If you change it, you not only have to change the bind variable, but you have to change the hard-coded SELECT clauses of the main query and the last sub-query (that is, got_pos).
MODEL or PL/SQL would probably be better ways to solve this problem. -
How to split the records into two parts
Hi experts,
I have a field with 75 char length, this field have records also, Now i want to split the field into two differnt fields. That means upto first 40 char goes to one field, from 41st char to 70 char goes to another field, for that how to split record into two parts.
Plz advice this,
MohanaHi,
Do the following:
f1 = fsource(40).
f2 = fsource+40(30).
where fsource is the 70 character original string and target strings are f1 (length 40) and f2 (length 30).
Cheers,
Aditya
Edited by: Aditya Laud on Feb 22, 2008 2:10 AM -
Dividing string into specific parts
Hi, I am trying to write a program that will convert a domain name into a Java package name, for instance forum.java.sun would be sun.java.forum.
I have the scanner class search for the periods, but all that does is find the index of the periods for me. Is there a way to divide the domain name into three parts? If so, would I have to store them in three seperate variables and then used the reverse() function to switch them around?
Thanks.Hi, I am trying to write a program that will convert
a domain name into a Java package name, for instance
forum.java.sun would be sun.java.forum.
I have the scanner class search for the periods, but
all that does is find the index of the periods for
me. Is there a way to divide the domain name into
three parts? If so, would I have to store them in
three seperate variables and then used the reverse()
function to switch them around?Scrap scanner and simply use String.split("\\.") to get the parts as an array. -
How do I cut a circle into equal parts?
I have a circle but I want to cut it into 5 equal parts and have each part on a seperate layer - kind of like a pie chart. Is there a quick and easy way to do this in CS6?
Not to my knowledge. No easy way, that is. I would think maybe easier done in Illstrator.
Good luck -
Split front panel into 2 parts
Hi
I need to spli the front page into 2 parts.On top I need to put a question with picture which are fixed and on bottom a page with scroll to go up and down I would like to put all my indicators and controls in that part but as I said the top part should be fixed and no one go up or down by the scroll of bottom page.really sorry for my late reply
many thanks for your help
just I have a problem.I have splitted my front page into 3 sections .In one section I put a waveform Graph the in the properties of the control I have selected "Fit Control to Pain" so the scroll bar for that pain disappered then I saved my file
after that I have made many changed and now I would like to have scroll bars in that pain again to scroll vertically and have many waveform graph controls but it is not possible and I cant get back scroll bars.Would uu please let me know is it possible to have scrolls for that pain again or I have to do all the design again.
Many thanks -
Easy Question: How to split concatenated string into multiple rows?
Hi folks,
this might be an easy question.
How can I split a concatenated string into multiple rows using SQL query?
INPUT:
select 'AAA,BBB,CC,DDDD' as data from dualDelimiter = ','
Expected output:
data
AAA
BBB
CCC
DDDDI'm looking for something kind of "an opposite for 'sys_connect_by_path'" function.
Thanks,
TomasHere is the SUBSTR/INSTR version of the solution:
SQL> WITH test_data AS
2 (
3 SELECT ',' || 'AAA,BBB,CC,DDDD' || ',' AS DATA FROM DUAL
4 )
5 SELECT SUBSTR
6 (
7 DATA
8 , INSTR
9 (
10 DATA
11 , ','
12 , 1
13 , LEVEL
14 ) + 1
15 , INSTR
16 (
17 DATA
18 , ','
19 , 1
20 , LEVEL + 1
21 ) -
22 INSTR
23 (
24 DATA
25 , ','
26 , 1
27 , LEVEL
28 ) - 1
29 ) AS NEW_STRING
30 FROM test_data
31 CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(DATA,'[^,]','')) - 1
32 /
NEW_STRING
AAA
BBB
CC
DDDD -
Split a string into multiple internal tables
Hi all,
I need to split a string based internal table into multiple internal tables based on some sub strings in that string based internal table...
High priority help me out...
eg...
a | jhkhjk | kljdskj |lkjdlj |
b | kjhdkjh | kldjkj |
c | jndojkok |
d |
this data which is in the application server file is brought into a internal table as a text. Now i need to send 'a' to one internal table, 'b' to one internal table, so on... help me
<Priority downgraded>
Edited by: Suhas Saha on Oct 12, 2011 12:24 PMHi pradeep,
eg...
a | jhkhjk | kljdskj |lkjdlj |
b | kjhdkjh | kldjkj |
c | jndojkok |
d |
As per your statement "Now i need to send 'a' to one internal table, 'b' to one internal table"
Do you want only a to one internal table and b to one internal table
OR
Do you want the whole row of the internal table i mean
a | jhkhjk | kljdskj |lkjdlj | to 1 internal table
Having the case of an internal table which is of type string,
1) Loop through the internal table. LOOP AT lt_tab INTO lwa_tab.
2) Ge the work area contents and get the first char wa_tab-string+0(1)
3) FIELD-SYMBOLS: <t_itab> TYPE ANY TABLE.
w_tabname = p_table.
CREATE DATA w_dref TYPE TABLE OF (w_tabname).
ASSIGN w_dref->* TO <t_itab>.
Follow the link
http://www.sap-img.com/ab030.htm
http://www.sapdev.co.uk/tips/dynamic-structure.htm
and then based on the sy-tabix values you will get that many number of internal table
<FS> = wa_tab-string+0(1)
append <FS>
OR
USE SPLIT statement at the relevant seperator
revert for further clarification
Thanks
Sri
Edited by: SRIKANTH P on Oct 12, 2011 12:36 PM -
Splitting a string into respective fields of dynamic internal table
Hi,
I've a string concatenated with a separator. I've to split the string and assign it to the respective fields of an internal table, which is dynamic.
Table name will be passed through selection screen. The data is coming from another system via RFC.
Eg : String ITAB :
100;89001;EN;Material1;MATERIAL1
100;89002;EN;Material2;MATERIAL2
The String ITAB may contain any master data. Let's say the above data is from MAKT table. So, I want to assign the above data to the respective fields of MAKT internal table(Dynamic).
I heard, this requirement can be achieved using some standard CLASS.
Please help me in doing this task.
Regards,
SunnyHello,
you can use dynamic programming for this issue, i.e.:
DATA: gv_table_name TYPE string,
gr_type_desc TYPE REF TO cl_abap_typedescr,
gr_struct_desc TYPE REF TO cl_abap_structdescr,
gr_table_desc TYPE REF TO cl_abap_tabledescr,
gv_t TYPE c,
gv_comp TYPE i,
gr_table_ref TYPE REF TO data,
gr_struc_ref TYPE REF TO data.
DATA: gt_itab TYPE TABLE OF string,
gt_split TYPE TABLE OF string,
gv_str TYPE string.
FIELD-SYMBOLS: <table> TYPE ANY TABLE,
<struct> TYPE ANY,
<comp> TYPE ANY.
APPEND '100;89001;EN;Material1;MATERIAL1' TO gt_itab.
APPEND '100;89002;EN;Material2;MATERIAL2' TO gt_itab.
"go!
gv_table_name = 'MAKT'.
cl_abap_tabledescr=>describe_by_name(
EXPORTING p_name = gv_table_name
RECEIVING p_descr_ref = gr_type_desc
EXCEPTIONS type_not_found = 4 ).
gr_struct_desc ?= gr_type_desc.
gr_table_desc = cl_abap_tabledescr=>create( gr_struct_desc ).
CREATE DATA gr_table_ref TYPE HANDLE gr_table_desc.
CREATE DATA gr_struc_ref TYPE HANDLE gr_struct_desc.
ASSIGN gr_table_ref->* TO <table>.
ASSIGN gr_struc_ref->* TO <struct>.
DESCRIBE FIELD <struct> TYPE gv_t COMPONENTS gv_comp.
LOOP AT gt_itab INTO gv_str.
CLEAR: gt_split.
SPLIT gv_str AT ';' INTO TABLE gt_split.
DO gv_comp TIMES.
READ TABLE gt_split INTO gv_str INDEX sy-index.
ASSIGN COMPONENT sy-index OF STRUCTURE <struct> TO <comp>.
<comp> = gv_str.
CLEAR gv_str.
ENDDO.
INSERT <struct> INTO TABLE <table>.
ENDLOOP.
After this code you will have all data in <table> field symbol in proper type.
Regards,
Jacek -
Cutting a Video Into Equal Parts: How?
I'm looking to cut a video into equal one second parts. Help?
Put the clip in the timeline. Move the playhead back to the beginning. Press Shift-right arrow. Press Control-V. Repeat until your hands hurt.
-
How to split a string into tokens and iterate through the tokens
Guys,
I want to split a string like 'Value1#Value2' using the delimiter #.
I want the tokens to be populated in a array-like (or any other convenient structure) so that I can iterate through them in a stored procedure. (and not just print them out)
I got a function on this link,
http://www.orafaq.com/forum/t/11692/0/
which returns a VARRAY. Can anybody help me how to iterate over the VARRAY, or suggest a different alternative to the split please ?
Thanks.RTFM: http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1146
or
http://www.oracle-base.com/articles/8i/Collections8i.php -
How to split a string into alfa-numerics and numerics ?
Thru I/O Assistant.vi I queried a GPIB frequency synthesizer and get a string " FRq99999.999999Hz " ( this is a micro Herz synthesizer and the query shows the correct value ).
The "9"'s are alfanumerics as well as the " FRq " and the " Hz ".
Thru a string indicator I can see this complete value on the front panel.
So far so good.
But now :
1.
How could I separate the numerics ( in string format ) out of this string and convert them into numerics in order to have them displayed in some numerics graph form ?
2.
How could I delete the " FRq " and the " Hz " out of the string, so that the " 9 " 's remain and could be converted into numerics ?
This result wil be the same as my question #1 but now ther
e will be no A/N remainder.
Thanks for any help.reteb wrote:
> Thru I/O Assistant.vi I queried a GPIB frequency synthesizer and get a
> string " FRq99999.999999Hz " ( this is a micro Herz synthesizer and
> the query shows the correct value ).
> The "9"'s are alfanumerics as well as the " FRq " and the " Hz ".
>
> 2.
> How could I delete the " FRq " and the " Hz " out of the string, so
> that the " 9 " 's remain and could be converted into numerics ?
> This result wil be the same as my question #1 but now there will be no
> A/N remainder.
Scan From String with a format string of "%.;%[^0-9]%f"
Explanation:
%.; : use point as decimal comma
%[0-9] : scan all characters not equal to 0 up to 9
%f : scan for floating point number using the decimal comma
indicated at the beginning.
Rolf Kal
bermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
Splitting a string into separate values, but the array length is variable
We are a cabinet manufacturer. I'm trying to write a report to show the location of individual hinges on a door. I have a string that will look something like these examples:
60, 540
60, 540, 956
60, 540, 956, 1340
It may have 2, 3, 4, or 5 locations. (Don't think I've ever seen one over 5).
So I have a formula that says:
Split({Doors.HingeCenterLines},',')[1]
This will return 60 - the first figure in my string.
I need to have all of them separated, but the critical thing is the last measurement. I need it to be the height of the door minus the last hinge location. So for an example, if I have a 1400mm tall door, the 4th example string listed above would be generated. I want my entries to look like this:
60
540
956
60
My string always references the hinge relationship to the bottom of the door, but for the top hinge only, I need it to be based on the distance from the top of the door.
Can anyone help with this? Thanks in advance!Try this code please:
whileprintingrecords;
local stringvar array arr := Split({Doors.HingeCenterLines},',');
local numbervar temp;
local stringvar fin_string;
local numbervar i;
For i := 1 to ubound(arr) do
If i = ubound(arr) then
temp := {Door_height} - tonumber(arr[i]);
fin_string := fin_string + totext(temp,0,"");
else
fin_string := fin_string + arr[i] + chr(13);
fin_string;
You can then right-click the field > Format Field > Common tab > Check the 'Can Grow' option.
-Abhilash
Maybe you are looking for
-
My powerbook is beeping every 2 seconds or so very quietly. I wasn't even sure it was the computer until the beeping stopped every time I put it in sleep mode. Anyone have this problem or know what it is?
-
Itunes missing msvcr80.dll
I have tried to repair my iTunes install on a Windows 8 machine and gotten this message. Help?
-
Compressing folders,sub-folders and files using java
Hello Friends, There's a small query if somebody could answer. I have to zip the contents of a folder which could have any hiearchy of folders and files. In short i want to do something what WinZip does but at runtime. Of how much help would be java.
-
Anyone else having extra long delivery time for the late 2013 macbook pro 15" 2.6ghz 1tb model? As of today feb 15 i have been waiting for 78 days. Finland doesn't have an official apple store (only authorized resellers) It was my mistake because i s
-
Error 12638-Credential retrieval failed
I am running net8 on a win98 machine and attempting to connect to a v8.1.6 db on an NT box. I run in a Novell environment and do not load the "Client for Microsoft Networks". When this client is loaded I can connect, otherwise I get the 12638 error.