源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JAVA中截取字符串substring用法详解

  • 时间:2022-04-17 04:28 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JAVA中截取字符串substring用法详解
[b]substring[/b] [code]public String substring(int beginIndex)[/code] 返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。 例如:
"unhappy".substring(2) returns "happy"
 
"Harbison".substring(3) returns "bison"
 
"emptiness".substring(9) returns "" (an empty string)
[b]参数:[/b] beginIndex - 开始处的索引(包括)。 [b]返回:[/b] 指定的子字符串。 [b]抛出:[/b] IndexOutOfBoundsException - 如果 beginIndex 为负或大于此 String 对象的长度。 [b]substring[/b] [code]public String substring(int beginIndex, int endIndex)[/code] 返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始, endIndex:到指定的 endIndex-1处结束。 示例: [code]"hamburger".substring(3,8) returns "burge"  "smiles".substring(0,5) returns "smile"[/code] [b]参数:[/b] beginIndex - 开始处的索引(包括)。 endindex 结尾处索引(不包括)。 [b]返回:[/b] 指定的子字符串。 [b]抛出:[/b] IndexOutOfBoundsException - 如果 beginIndex 为负,或length大于字符串长度。 示例 [code]var str="Hello world!" document.write(str.substring(1,3));[/code] 上面返回字符串:"el"; str.substring(1,2) //返回e str.substring(1) //返回"ello world"; 还有此函数中会出现奇怪的现象,当出现str.substring(5,0); 这又是怎么回事,不过返回的是"hello", str.substring(5,1) //返回"ello",截去了第一位,返回余下的. 可见substring(start,end),可以有不同的说明,即start可以是要返回的长度,end是所要去掉的多少个字符(从首位开始). 在JS中,substr(start,length),用得较方便. [b]编辑本段C#中[/b] 变量.Substring(参数1,参数2); 截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如: [code]string s1 = str.Substring(0,2);[/code] [b]C#中有两个重载函数[/b] 举例如下代码,VS2005编译通过
using System;
 
using System.Collections.Generic;
 
using System.Text;
 
namespace sln_sub
 
{
 
class Program
 
{
 
static void Main(string[] args)
 
{
string myString = "A quick fox is jumping over the lazy dog";
//Substring()在C#中有两个重载函数 //分别如下示例 [code]string subString1 = myString.Substring(0);[/code] //如果传入参数为一个长整, 且大于等于0, //则以这个长整的位置为起始, //截取之后余下所有作为字串. //如若传入值小于0, //系统会抛出ArgumentOutOfRange异常 //表明参数范围出界 [code]string subString2 = myString.Substring(0, 11);[/code] //如果传入了两个长整参数, //前一个为参数子串在原串的起始位置 //后一个参数为子串的长度 //如不合条件同样出现上述异常
Console.WriteLine(subString1);
Console.WriteLine(subString2);
Console.ReadLine(); 
} 
}
}
[b]程序输出的结果:[/b] [code]A quick fox is jumping over the lazy dog[/code] [code]A quick fox[/code] 另外,求字符a在字符串A中的位置:A.Indexof('a')。 [b]编辑本段js用法[/b] 在JS中, 函数声明: stringObject.substring(start,stop) start是在原字符串检索的开始位置,stop是检索的终止位置,返回结果中不包括stop所指字符. [b]编辑本段CB用法[/b] [b]用途[/b] [code]Returns the substring at the specified location within a String object.[/code] 函数用法及举例 [code]strVariable.substring(start, end)[/code] [code]"String Literal".substring(start, end)[/code] 用法说明:返回一个字串,其中start是起始的index,end是终止的index,返回的字串包含起始index的字符,但是不包含end的字符。这个是string类下的一个method。 用法实例
function SubstringDemo(){
 
var ss; //Declare variables.
 
var s = "The rain in Spain falls mainly in the plain..";
 
ss = s.substring(12, 17); //Get substring.
 
return
(ss); //Return substring.

}
希望本篇文章对需要学习的朋友有所帮助
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部