字符串string的相关应用

  之所以抛弃char* 的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,

而且作为一个泛型类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用 = 进行赋值操作,== 进行比较,+ 做串联。

我们尽可以把它看成是C++的基本数据类型。

  今日讲点:

    string中的内容访问

    string类的常用函数

    string字符串的比较问题

 

 声明一个C++字符串:

  string str;//直接声明,很简单

 

对于string内容的访问问题

  1 和c语言的访问方式一样,使用数组下标进行访问

  c语言的代码

 

#include <stdio.h>
int main()
{
	char ch[10];
	gets(ch);
	for(int i=0;i<10;i++)
	{
		printf("%c ",ch[i]);
	}
	printf("\n");
	return 0;
} 

  

  c++的代码

#include<cstring>
#include <iostream>
using namespace std;
int main()
{
	string str;
	cin>>str;
	int len=str.length();
	for(int i=0;i<len;i++)
	{
		cout<<str[i]<<" ";
	}
	cout<<endl;
	return 0;
}

  

  2通过迭代器进行访问

    一般的情况下采用第一种方式就可以满足访问的要求,但是有些函数比如insert()  erase()则要求以迭代器为参数。

#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
	string str="abcdefgh";
	string::iterator it;
	for(it=str.begin();it!=str.end();it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;
	return 0;
} 

  

对于string类的常用函数

  string属于c++的字符串类,那么类就会存在构造函数(本块了解下就可以)

  a)    string s;  //生成一个空字符串s

      `b)    string s(str) //拷贝构造函数 生成str的复制品

       c)    string s(str,stridx) //将字符串str内“始于位置stridx”的部分当作字符串的初值 
       d)    string s(str,stridx,strlen) //将字符串str内“始于stridx且长度顶多strlen”的部分作为字符串的初值
       e)    string s(cstr) //将C字符串作为s的初值
        f)    string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。
       g)    string s(num,c) //生成一个字符串,包含num个c字符
       h)    string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值
       i)    s.~string() //销毁所有字符,释放内存

#include <iostream>
#include <string>
using namespace std;
int main ( )
{
    string str;  //定义了一个空字符串str
    str = "Hello world";   // 给str赋值为"Hello world"
    char cstr[] = "abcde";  //定义了一个C字符串
    string s1(str);       //调用复制构造函数生成s1,s1为str的复制品
    cout<<s1<<endl;
    string s2(str,6);     //将str内,开始于位置6的部分当作s2的初值
    cout<<s2<<endl;
    string s3(str,6,3);  //将str内,开始于6且长度顶多为3的部分作为s3的初值
        cout<<s3<<endl;
    string s4(cstr);   //将C字符串作为s4的初值
    cout<<s4<<endl;
    string s5(cstr,3);  //将C字符串前3个字符作为字符串s5的初值。
    cout<<s5<<endl;
    string s6(5,'A');  //生成一个字符串,包含5个'A'字符
    cout<<s6<<endl;
    string s7(str.begin(),str.begin()+5); //区间str.begin()和str.begin()+5内的字符作为初值
    cout<<s7<<endl;
    return 0;
}

  

 

  string的比较等操作

        你可以用 ==、>、<、>=、<=、和!=比较字符串,可以用+或者+=操作符连接两个字符串,并且可以用[]获取特定的字符。

     

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str;
    cout << "Please input your name:"<<endl;
    cin >> str;
    if( str == "Li" )   // 字符串相等比较
        cout << "you are Li!"<<endl;
    else if( str != "Wang" )  // 字符串不等比较
        cout << "you are not Wang!"<<endl;
    else if( str < "Li")     // 字符串小于比较,>、>=、<=类似
        cout << "your name should be ahead of Li"<<endl;
    else
        cout << "your name should be after of Li"<<endl;
    str += ", Welcome!";  // 字符串+=
    cout << str<<endl;
    for(int i = 0 ; i < str.size(); i ++)
        cout<<str[i];  // 类似数组,通过[]获取特定的字符
    return 0;
}

 

    

  下面介绍string类的相关函数

                 +=,append(),push_back() //在尾部添加字符

                  insert() //插入字符

                  erase() //删除字符

                  clear() //删除全部字符 

                  replace() //替换字符

      size(),length()  //返回字符数量

       max_size() //返回字符的可能最大个数

       empty()  //判断字符串是否为空

       substr() //返回某个子字符串

      find()//查询字串第一次出现的位置下标

      查找函数

        begin() end() //提供类似STL的迭代器支持

        rbegin() rend() //逆向迭代器

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    string str="1234567";
    int len1=str.length();
    int len2=str.size();
    cout<<"字符串的长度:"<<len1<<"  "<<len2<<endl;
     //insert插入字符串
     str.insert(3,"abcd");//在str[3]处开始插入abcd; 
     cout<<str<<endl;
     
     //erase(it)用于删除单个元素,it为需要删除的元素迭代器
     string str1="abcdefgh";
     str1.erase(str1.begin()+3);//删除第三号位 str1[3]; 
     cout<<str1<<endl; 
     //删除[str1.begin()+2,str1.end()-1)内的元素
     str1.erase(str1.begin()+2,str1.end()-1);
     cout<<str1<<endl;
     
     string str2="abcdefgh";
     //str2.erase(3,2);
     str2.erase(3,2);
     cout<<str2<<endl;
    return 0;
}

 

 

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
    string str="abcdefghi";
    int len=str.length();
    cout<<len<<endl;
    str.clear();
    int len2=str.length();
    cout<<len2<<endl;
    return 0;
}

 

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main()
{
    //substr(pos,len)返回从pos号开始,长度为len的字串 
    string str="Thank you for your smile";
    cout<<str.substr(0,5)<<endl;
    cout<<str.substr(14,4)<<endl;
    cout<<str.substr(19,5)<<endl; 
    cout<<endl<<endl;
    
    //replace() str.replace(pos,len,str2)把str从pos号位开始,长度为len的字符串替换为str2
    //str.replace(it1,it2,str2)把str的迭代器[it1,it2)范围的子串替换成str2
    string str1="Maybe you will turn around";
    string str2="will not";
    string str3="surely";
    cout<<str1.replace(10,4,str2)<<endl;
    cout<<str1.replace(str1.begin(),str1.begin()+5,str3)<<endl; 
    return 0;
} 

 

 

Java String 类

字符串广泛应用 在Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。

注意:String 类是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了

如果需要对字符串做很多修改,那么应该选择使用 StringBuffer & StringBuilder 类

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        char helloarray[]={'h','e','l','l','o'};
        String hellostring =new String(helloarray);
        System.out.println(helloarray);
    }
}

 

 

字符串长度

用于获取有关对象的信息的方法称为访问器方法。

String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        String str="hello world";
        System.out.println(str.length());
    }
}

连接字符串

String 类提供了连接两个字符串的方法:

string1.concat(string2);

返回 string2 连接 string1 的新字符串

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        String str="hello world";
        String str1="nhjc";
        String str3=str.concat(str1);
        System.out.println(str3);
    }
}

 

String 方法

下面是 String 类支持的方法,更多详细

 

SN(序号)方法描述
1char charAt(int index)
返回指定索引处的 char 值。
2int compareTo(Object o)
把这个字符串和另一个对象比较。
3int compareTo(String anotherString)
按字典顺序比较两个字符串。
4int compareToIgnoreCase(String str)
按字典顺序比较两个字符串,不考虑大小写。
5String concat(String str)
将指定字符串连接到此字符串的结尾。
6boolean contentEquals(StringBuffer sb)
当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。
7static String copyValueOf(char[] data)
返回指定数组中表示该字符序列的 String。
8static String copyValueOf(char[] data, int offset, int count)
返回指定数组中表示该字符序列的 String。
9boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结束。
10boolean equals(Object anObject)
将此字符串与指定的对象比较。
11boolean equalsIgnoreCase(String anotherString)
将此 String 与另一个 String 比较,不考虑大小写。
12byte[] getBytes()
 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
13byte[] getBytes(String charsetName)
使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
14void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
将字符从此字符串复制到目标字符数组。
15int hashCode()
返回此字符串的哈希码。
16int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。
17int indexOf(int ch, int fromIndex)
返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
18int indexOf(String str)
 返回指定子字符串在此字符串中第一次出现处的索引。
19int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
20String intern()
 返回字符串对象的规范化表示形式。
21int lastIndexOf(int ch)
 返回指定字符在此字符串中最后一次出现处的索引。
22int lastIndexOf(int ch, int fromIndex)
返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
23int lastIndexOf(String str)
返回指定子字符串在此字符串中最右边出现处的索引。
24int lastIndexOf(String str, int fromIndex)
 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
25int length()
返回此字符串的长度。
26boolean matches(String regex)
告知此字符串是否匹配给定的正则表达式。
27boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
28boolean regionMatches(int toffset, String other, int ooffset, int len)
测试两个字符串区域是否相等。
29String replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
30String replaceAll(String regex, String replacement)
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
31String replaceFirst(String regex, String replacement)
 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
32String[] split(String regex)
根据给定正则表达式的匹配拆分此字符串。
33String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。
34boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开始。
35boolean startsWith(String prefix, int toffset)
测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
36CharSequence subSequence(int beginIndex, int endIndex)
 返回一个新的字符序列,它是此序列的一个子序列。
37String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。
38String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。
39char[] toCharArray()
将此字符串转换为一个新的字符数组。
40String toLowerCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41String toLowerCase(Locale locale)
 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42String toString()
 返回此对象本身(它已经是一个字符串!)。
43String toUpperCase()
使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44String toUpperCase(Locale locale)
使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45String trim()
返回字符串的副本,忽略前导空白和尾部空白。
46static String valueOf(primitive data type x)
返回给定data type类型x参数的字符串表示形式。

 

char charAt(int index)

charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
      String str ="Hello world";
      System.out.println(str.charAt(1));//输出e
    }
}

 

 

Java compareTo() 方法

compareTo() 方法用于两种方式的比较:

  • 字符串与对象进行比较。
  • 按字典顺序比较两个字符串。
int compareTo(Object o)
 
或
 
int compareTo(String anotherString)

 

返回值

返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方。

  • 如果参数字符串等于此字符串,则返回值 0;
  • 如果此字符串小于字符串参数,则返回一个小于 0 的值;
  • 如果此字符串大于字符串参数,则返回一个大于 0 的值。
package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";

        int result = str1.compareTo( str2 );
        System.out.println(result);

        result = str2.compareTo( str3 );
        System.out.println(result);

        result = str3.compareTo( str1 );
        System.out.println(result);
    }
}

 

 

Java compareToIgnoreCase() 方法

compareToIgnoreCase() 方法用于按字典顺序比较两个字符串,不考虑大小写。

语法

int compareToIgnoreCase(String str)

返回值

  • 如果参数字符串等于此字符串,则返回值 0;
  • 如果此字符串小于字符串参数,则返回一个小于 0 的值;
  • 如果此字符串大于字符串参数,则返回一个大于 0 的值。
 

Java concat() 方法

concat() 方法用于将指定的字符串参数连接到字符串上。

语法

public String concat(String s)

参数

  • s -- 要连接的字符串。

返回值

返回连接后的新字符串。

 

Java contentEquals() 方法

contentEquals() 方法用于将此字符串与指定的 StringBuffer 比较。

语法

public boolean contentEquals(StringBuffer sb)

参数

  •  -- 要与字符串比较的 StringBuffer。

返回值

如字符串与指定 StringBuffer 表示相同的字符序列,则返回 true;否则返回 false。

实例

public class Test {
    public static void main(String args[]) {
        String str1 = "String1";
        String str2 = "String2";
        StringBuffer str3 = new StringBuffer( "String1");

        boolean  result = str1.contentEquals( str3 );
        System.out.println(result);
          
        result = str2.contentEquals( str3 );
        System.out.println(result);
    }
}

 

 

Java copyValueOf() 方法

copyValueOf() 方法有两种形式:

  • public static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的字符串。

  • public static String copyValueOf(char[] data, int offset, int count): 返回指定数组中表示该字符序列的 字符串。

语法

public static String copyValueOf(char[] data)  public static String copyValueOf(char[] data, int offset, int count)

参数

  • data -- 字符数组。

  • offset -- 子数组的初始偏移量。。

  • count -- 子数组的长度。

返回值

返回指定数组中表示该字符序列的字符串。

public class Test {
    public static void main(String args[]) {
        char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'r', 'u', 'n', 'o', 'o', 'b'};
        String Str2 = "";

        Str2 = Str2.copyValueOf( Str1 );
        System.out.println("返回结果:" + Str2);

        Str2 = Str2.copyValueOf( Str1, 2, 6 );
        System.out.println("返回结果:" + Str2);
    }
}

 

 

返回结果:hello runoob
返回结果:llo ru

 

Java endsWith() 方法

endsWith() 方法用于测试字符串是否以指定的后缀结束。

语法

public boolean endsWith(String suffix)

参数

  • suffix -- 指定的后缀。

返回值

如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。注意,如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        String Str = new String();
        Str="Hello world";
        boolean retVal;

        retVal = Str.endsWith( "world" );
        System.out.println("返回值 = " + retVal );

        retVal = Str.endsWith( "com" );
        System.out.println("返回值 = " + retVal );
    }
}

 

Java equals() 方法

语法

public boolean equals(Object anObject)

参数

  • anObject -- 与字符串进行比较的对象。

返回值

如果给定对象与字符串相等,则返回 true;否则返回 false。

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("runoob");
        String Str2 = Str1;
        String Str3 = new String("runoob");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );

        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );
    }
}

 

 

 

Java equalsIgnoreCase() 方法

equalsIgnoreCase() 方法用于将字符串与指定的对象比较,不考虑大小写。

语法

public boolean equalsIgnoreCase(String anotherString)

参数

  • anObject -- 与字符串进行比较的对象。

返回值

如果给定对象与字符串相等,则返回 true;否则返回 false。

 

 

Java hashCode() 方法

hashCode() 方法用于返回字符串的哈希码。

字符串对象的哈希码根据以下公式计算:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0。

语法

public int hashCode()

参数

  • 无。

返回值

返回对象的哈希码值。

package com.nhjc.byc;
import java.lang.String;
public class Main {
    public static void main(String[] args) {
        String Str = new String();
        Str="Hello world";
        System.out.println("字符串的哈希码为 :" + Str.hashCode() );
    }
}

 

转载于:https://www.cnblogs.com/byczyz/p/10779907.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值